@primer-io/primer-js 0.8.1 → 0.8.2

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 CHANGED
@@ -1,5 +1,11 @@
1
1
  # @primer-io/primer-js
2
2
 
3
+ ## 0.8.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 51f6174: fix: find slotted accordion toggle by slot name - show other payment methods component - and dispatch vault:selection-change event for the vault submit button
8
+
3
9
  ## 0.8.1
4
10
 
5
11
  ### Patch Changes
@@ -286,7 +286,7 @@
286
286
  {
287
287
  "kind": "variable",
288
288
  "name": "_e",
289
- "default": "class extends v{constructor(){super(...arguments);this.vaultManager=null;this.contextEventsController=null;this.hasSlottedToggle=!1;this.isExpanded=!1;this._isHandlingContextEvent=!1;this._contextToggleListener=null;this.handleToggleSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasSlottedToggle=i.length>0};this.handleSlotButtonClick=e=>{let i=e.target.closest(\"button, primer-button\");if(!i)return;let n=i;this.isToggleButton(n)&&(e.preventDefault(),this.toggleAccordion())};this.handleDirectToggle=e=>{let a=e.detail?.action;a===\"expand\"?this.expand():a===\"collapse\"?this.collapse():this.toggleAccordion()};this.handleContextToggle=e=>{if(!this._isHandlingContextEvent){this._isHandlingContextEvent=!0;try{if(e.target!==this){e.stopPropagation();let a=e.detail?.action;a===\"expand\"?this.expand():a===\"collapse\"?this.collapse():this.toggleAccordion()}}finally{this._isHandlingContextEvent=!1}}}}isToggleButton(e){let a=e.tagName.toLowerCase(),i=a===\"button\",n=a===\"primer-button\";return i&&(e.getAttribute(\"type\")===\"button\"||e.hasAttribute(\"data-toggle\"))||n&&e.hasAttribute(\"data-toggle\")}toggleAccordion(){this.hasSlottedToggle?(this.isExpanded=!this.isExpanded,this.dispatchExpandedEvent(this.isExpanded)):this.collapsableElement&&(this.collapsableElement.isExpanded?this.collapsableElement.collapse():this.collapsableElement.expand())}dispatchExpandedEvent(e){this.dispatchEvent(new CustomEvent(\"show-other-payments-toggled\",{bubbles:!0,composed:!0,detail:{expanded:e}}))}expand(){this.hasSlottedToggle?this.isExpanded||(this.isExpanded=!0,this.dispatchExpandedEvent(!0)):this.collapsableElement?.expand()}collapse(){this.hasSlottedToggle?this.isExpanded&&(this.isExpanded=!1,this.dispatchExpandedEvent(!1)):this.collapsableElement?.collapse()}setupContextEventListeners(){this.contextEventsController?.host&&this._contextToggleListener&&this.contextEventsController.host.addEventListener(\"primer:show-other-payments-toggle\",this._contextToggleListener)}cleanupContextEventListeners(){this.contextEventsController?.host&&this._contextToggleListener&&this.contextEventsController.host.removeEventListener(\"primer:show-other-payments-toggle\",this._contextToggleListener)}connectedCallback(){super.connectedCallback(),this.isExpanded=this.vaultManager?.vaultedPaymentMethods.length===0,this.addEventListener(\"click\",this.handleSlotButtonClick),this.addEventListener(\"primer:show-other-payments-toggle\",this.handleDirectToggle),this._contextToggleListener=e=>{this.handleContextToggle(e)},this.setupContextEventListeners()}disconnectedCallback(){this.removeEventListener(\"click\",this.handleSlotButtonClick),this.removeEventListener(\"primer:show-other-payments-toggle\",this.handleDirectToggle),this.cleanupContextEventListeners(),super.disconnectedCallback()}render(){if(this.vaultManager?.isLoading)return g;let e=this.vaultManager?.showEmptyState||this.vaultManager?.vaultedPaymentMethods.length;return!this.vaultManager||!this.vaultManager.enabled||!e?p`<slot name=\"other-payments\"></slot>`:p`<div class=\"other-payment-methods-container\"><slot name=\"show-other-payments-toggle-button\" @slotchange=${this.handleToggleSlotChange} ></slot>${L(!this.hasSlottedToggle,()=>p`<primer-collapsable buttonVariant=\"secondary\" .expanded=\"${this.vaultManager?.vaultedPaymentMethods.length===0}\" .header=\"${b(\"navigateToPaymentMethods\",{id:\"navigateToPaymentMethods\"})}\" ><div class=\"other-payment-methods-content\"><slot name=\"other-payments\"></slot></div></primer-collapsable>`,()=>p`<div class=\"collapsable-wrapper ${this.isExpanded?\"expanded\":\"\"}\" role=\"region\" aria-labelledby=\"custom-toggle-button\" ><div class=\"collapsable-content\"><div class=\"other-payment-methods-content\"><slot name=\"other-payments\"></slot></div></div></div>`)}</div>`}}"
289
+ "default": "class extends v{constructor(){super(...arguments);this.vaultManager=null;this.contextEventsController=null;this.hasSlottedToggle=!1;this.isExpanded=!1;this._isHandlingContextEvent=!1;this._contextToggleListener=null;this.handleToggleSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasSlottedToggle=i.length>0};this.handleSlotButtonClick=e=>{let i=e.target.closest(\"button, primer-button\");if(!i)return;let n=i;this.isToggleButton(n)&&(e.preventDefault(),this.toggleAccordion())};this.handleDirectToggle=e=>{let a=e.detail?.action;a===\"expand\"?this.expand():a===\"collapse\"?this.collapse():this.toggleAccordion()};this.handleContextToggle=e=>{if(!this._isHandlingContextEvent){this._isHandlingContextEvent=!0;try{if(e.target!==this){e.stopPropagation();let a=e.detail?.action;a===\"expand\"?this.expand():a===\"collapse\"?this.collapse():this.toggleAccordion()}}finally{this._isHandlingContextEvent=!1}}}}isToggleButton(e){let a=this.shadowRoot?.querySelector('slot[name=\"show-other-payments-toggle-button\"]');return a?a.assignedElements({flatten:!0}).some(n=>n===e||n.contains(e)):!1}toggleAccordion(){this.hasSlottedToggle?(this.isExpanded=!this.isExpanded,this.dispatchExpandedEvent(this.isExpanded)):this.collapsableElement&&(this.collapsableElement.isExpanded?this.collapsableElement.collapse():this.collapsableElement.expand())}dispatchExpandedEvent(e){this.dispatchEvent(new CustomEvent(\"primer:show-other-payments-toggled\",{bubbles:!0,composed:!0,detail:{expanded:e}}))}expand(){this.hasSlottedToggle?this.isExpanded||(this.isExpanded=!0,this.dispatchExpandedEvent(!0)):this.collapsableElement?.expand()}collapse(){this.hasSlottedToggle?this.isExpanded&&(this.isExpanded=!1,this.dispatchExpandedEvent(!1)):this.collapsableElement?.collapse()}setupContextEventListeners(){this.contextEventsController?.host&&this._contextToggleListener&&this.contextEventsController.host.addEventListener(\"primer:show-other-payments-toggle\",this._contextToggleListener)}cleanupContextEventListeners(){this.contextEventsController?.host&&this._contextToggleListener&&this.contextEventsController.host.removeEventListener(\"primer:show-other-payments-toggle\",this._contextToggleListener)}connectedCallback(){super.connectedCallback(),this.isExpanded=this.vaultManager?.vaultedPaymentMethods.length===0,this.addEventListener(\"click\",this.handleSlotButtonClick),this.addEventListener(\"primer:show-other-payments-toggle\",this.handleDirectToggle),this._contextToggleListener=e=>{this.handleContextToggle(e)},this.setupContextEventListeners()}disconnectedCallback(){this.removeEventListener(\"click\",this.handleSlotButtonClick),this.removeEventListener(\"primer:show-other-payments-toggle\",this.handleDirectToggle),this.cleanupContextEventListeners(),super.disconnectedCallback()}render(){if(this.vaultManager?.isLoading)return g;let e=this.vaultManager?.showEmptyState||this.vaultManager?.vaultedPaymentMethods.length;return!this.vaultManager||!this.vaultManager.enabled||!e?p`<slot name=\"other-payments\"></slot>`:p`<div class=\"other-payment-methods-container\"><slot name=\"show-other-payments-toggle-button\" @slotchange=${this.handleToggleSlotChange} ></slot>${L(!this.hasSlottedToggle,()=>p`<primer-collapsable buttonVariant=\"secondary\" .expanded=\"${this.vaultManager?.vaultedPaymentMethods.length===0}\" .header=\"${b(\"navigateToPaymentMethods\",{id:\"navigateToPaymentMethods\"})}\" ><div class=\"other-payment-methods-content\"><slot name=\"other-payments\"></slot></div></primer-collapsable>`,()=>p`<div class=\"collapsable-wrapper ${this.isExpanded?\"expanded\":\"\"}\" role=\"region\" aria-labelledby=\"custom-toggle-button\" ><div class=\"collapsable-content\"><div class=\"other-payment-methods-content\"><slot name=\"other-payments\"></slot></div></div></div>`)}</div>`}}"
290
290
  },
291
291
  {
292
292
  "kind": "variable",
@@ -4721,6 +4721,25 @@
4721
4721
  ],
4722
4722
  "description": "Dispatch vault methods update event.\nCalled when vaulted payment methods are loaded or updated."
4723
4723
  },
4724
+ {
4725
+ "kind": "method",
4726
+ "name": "dispatchVaultSelectionChange",
4727
+ "return": {
4728
+ "type": {
4729
+ "text": "void"
4730
+ }
4731
+ },
4732
+ "parameters": [
4733
+ {
4734
+ "name": "paymentMethodId",
4735
+ "type": {
4736
+ "text": "string | null"
4737
+ },
4738
+ "description": "ID of the selected payment method, or null if deselected"
4739
+ }
4740
+ ],
4741
+ "description": "Dispatch vault selection change event.\nCalled when a vaulted payment method is selected or deselected."
4742
+ },
4724
4743
  {
4725
4744
  "kind": "method",
4726
4745
  "name": "dispatchVaultSubmit",
@@ -4803,6 +4822,25 @@
4803
4822
  }
4804
4823
  ],
4805
4824
  "description": "Handle external show other payments toggle events and forward them through the event system.\nThis method provides a centralized way to process external toggle events\nthat come from custom buttons or external triggers."
4825
+ },
4826
+ {
4827
+ "kind": "method",
4828
+ "name": "dispatchShowOtherPaymentsToggled",
4829
+ "return": {
4830
+ "type": {
4831
+ "text": "void"
4832
+ }
4833
+ },
4834
+ "parameters": [
4835
+ {
4836
+ "name": "expanded",
4837
+ "type": {
4838
+ "text": "boolean"
4839
+ },
4840
+ "description": "Whether the accordion is now expanded"
4841
+ }
4842
+ ],
4843
+ "description": "Dispatch show other payments toggled event.\nCalled when the \"Show other ways to pay\" accordion state changes."
4806
4844
  }
4807
4845
  ]
4808
4846
  }
@@ -12936,7 +12974,7 @@
12936
12974
  }
12937
12975
  }
12938
12976
  ],
12939
- "description": "Determines if a button is a toggle button based on its attributes"
12977
+ "description": "Determines if a button is a toggle button based on its slot assignment\nOnly buttons in the 'show-other-payments-toggle-button' slot are toggle buttons\nThis prevents accidentally capturing other buttons like submit buttons"
12940
12978
  },
12941
12979
  {
12942
12980
  "kind": "field",
@@ -13033,7 +13071,7 @@
13033
13071
  ],
13034
13072
  "events": [
13035
13073
  {
13036
- "name": "show-other-payments-toggled",
13074
+ "name": "primer:show-other-payments-toggled",
13037
13075
  "type": {
13038
13076
  "text": "CustomEvent"
13039
13077
  }
@@ -461,7 +461,7 @@ export type ShowOtherPaymentsComponentProps = {
461
461
  /** Consume the events context for external control */
462
462
  contextEventsController?: EventsContextType;
463
463
  /** */
464
- "onshow-other-payments-toggled"?: (e: CustomEvent<CustomEvent>) => void;
464
+ "onprimer:show-other-payments-toggled"?: (e: CustomEvent<CustomEvent>) => void;
465
465
  };
466
466
 
467
467
  export type VaultManagerComponentProps = {
@@ -1067,7 +1067,7 @@ export type CustomElements = {
1067
1067
  *
1068
1068
  *
1069
1069
  * ### **Events:**
1070
- * - **show-other-payments-toggled**
1070
+ * - **primer:show-other-payments-toggled**
1071
1071
  *
1072
1072
  * ### **Methods:**
1073
1073
  * - **expand(): _void_** - Public API: Expand the accordion programmatically
@@ -1987,6 +1987,9 @@ export interface ShowOtherPaymentsTogglePayload {
1987
1987
  action?: "toggle" | "expand" | "collapse";
1988
1988
  source?: string;
1989
1989
  }
1990
+ export interface ShowOtherPaymentsToggledPayload {
1991
+ expanded: boolean;
1992
+ }
1990
1993
  export interface PrimerEvents {
1991
1994
  "primer:state-change": CustomEvent<SdkStateContextType>;
1992
1995
  "primer:methods-update": CustomEvent<InitializedPayments>;
@@ -2020,8 +2023,13 @@ export interface PrimerEvents {
2020
2023
  vaultedPayments: InitializedVaultedPayments;
2021
2024
  timestamp: number;
2022
2025
  }>;
2026
+ "primer:vault:selection-change": CustomEvent<{
2027
+ paymentMethodId: string | null;
2028
+ timestamp: number;
2029
+ }>;
2023
2030
  "primer:vault-submit": CustomEvent<VaultSubmitPayload>;
2024
2031
  "primer:show-other-payments-toggle": CustomEvent<ShowOtherPaymentsTogglePayload>;
2032
+ "primer:show-other-payments-toggled": CustomEvent<ShowOtherPaymentsToggledPayload>;
2025
2033
  }
2026
2034
  declare class PrimerEventsController implements ReactiveController {
2027
2035
  host: ReactiveControllerHost & LitElement;
@@ -2077,6 +2085,13 @@ declare class PrimerEventsController implements ReactiveController {
2077
2085
  * @param vaultedPayments - Wrapper containing filtered vaulted payment methods
2078
2086
  */
2079
2087
  dispatchVaultMethodsUpdate(vaultedPayments: InitializedVaultedPayments): void;
2088
+ /**
2089
+ * Dispatch vault selection change event.
2090
+ * Called when a vaulted payment method is selected or deselected.
2091
+ *
2092
+ * @param paymentMethodId - ID of the selected payment method, or null if deselected
2093
+ */
2094
+ dispatchVaultSelectionChange(paymentMethodId: string | null): void;
2080
2095
  /**
2081
2096
  * Dispatch vault submit event.
2082
2097
  * Called when a vault payment submission is triggered.
@@ -2103,6 +2118,13 @@ declare class PrimerEventsController implements ReactiveController {
2103
2118
  * @param eventDetails - The event details to forward, including action and source information
2104
2119
  */
2105
2120
  handleExternalShowOtherPaymentsToggle(eventDetails: ShowOtherPaymentsTogglePayload): void;
2121
+ /**
2122
+ * Dispatch show other payments toggled event.
2123
+ * Called when the "Show other ways to pay" accordion state changes.
2124
+ *
2125
+ * @param expanded - Whether the accordion is now expanded
2126
+ */
2127
+ dispatchShowOtherPaymentsToggled(expanded: boolean): void;
2106
2128
  }
2107
2129
  export type AnalyticsContextType = AnalyticsUtils | null;
2108
2130
  export type EventsContextType = PrimerEventsController | null;
@@ -4904,7 +4926,9 @@ declare class ShowOtherPaymentsComponent extends LitElement {
4904
4926
  */
4905
4927
  private handleToggleSlotChange;
4906
4928
  /**
4907
- * Determines if a button is a toggle button based on its attributes
4929
+ * Determines if a button is a toggle button based on its slot assignment
4930
+ * Only buttons in the 'show-other-payments-toggle-button' slot are toggle buttons
4931
+ * This prevents accidentally capturing other buttons like submit buttons
4908
4932
  */
4909
4933
  private isToggleButton;
4910
4934
  /**
@@ -148,9 +148,9 @@ ${i}`;function cc(r,t,e){if(e?.status&&e.status>=400&&e.status<500)return!1;if(e
148
148
  </div>
149
149
  </body>
150
150
  </html>
151
- `;async function Mc(r,t){let e=r.configuration.paymentMethods.map(i=>{if(!t.includes(i.type))return null;if(R.debug("Initializing payment method:",i.type),i.implementationType==="WEB_REDIRECT")return new Xr(i,r);if(i.type===de.PAYMENT_CARD)return new wa(i,r);if(i.type===de.PAYPAL)return new Da(i,r);if(i.type===de.APPLE_PAY)return new xa(i,r);if(i.type===de.GOOGLE_PAY)return new Ba(i,r);if(i.type===de.ADYEN_BLIK)return new _a(i,r)}).map(async i=>{if(!i)return null;try{return await i.setup()?i:null}catch(n){return R.warn(`Failed to initialize payment method ${i.config.type}:`,n),null}});return(await Promise.all(e)).filter(i=>!!i)}function Ec(r,t,e){if(!t.configuration.clientSession.customer?.customerId)throw new V({message:"You must provide a `customerId` in the client session to use the Vault Manager."});let a=[];return{async fetchVaultedPaymentMethods(){let{data:i,error:n}=await t.pciApi.getPaymentInstruments();if(n)throw n;if(!i)throw new V({code:Ta.VAULT_ERROR,message:"Missing vaulted payment methods data"});return a=i.data,a},async deleteVaultedPaymentMethod(i){if(!a.find(s=>s.id===i))throw new V({code:Ta.VAULT_ERROR,message:"deleteVaultedPaymentMethod: the id provided doesn't match any vaulted payment method"});let{error:o}=await t.pciApi.deletePaymentInstrument(i);if(o)throw o;a=a.filter(s=>s.id!==i)},async startPaymentFlow(i){let n=a.find(s=>s.id===i);if(!n)throw new V({code:Ta.VAULT_ERROR,message:"startPaymentFlow: the id provided doesn't match any vaulted payment method"});let o=e.find(s=>s.config.type===n.paymentMethodType);if(!o)throw new V({code:Ta.TOKENIZATION_ERROR,message:`Payment instrument type ${n.paymentInstrumentType} is not recognized or not supported.`});await Ga(r,o,n)},async createCvvInput(i){let n={blur:new Set,change:new Set,focus:new Set},o,s=Xt(t.checkoutSessionId,cn);await new Promise(h=>{s.onload=()=>{h()},(typeof i.container=="string"?document.querySelector(i.container):i.container)?.appendChild(s)}),Wr(s,i.style),s.setAttribute("title",i.ariaLabel||"");let l=li({namespace:`${t.checkoutSessionId}-${cn}`,onMessage:h=>{let A=C=>h(C.data);return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},sendMessage:h=>{s.contentWindow.postMessage(h,"*")}});function c(h,A){h!=="metadata"&&n[h].add(A)}l.setOnFocus(()=>{n.focus.forEach(h=>h())}),l.setOnBlur(()=>{n.blur.forEach(h=>h())}),l.setOnInput(h=>{o=h,n.change.forEach(A=>A())}),l.setCardNetwork(i.cardNetwork??""),l.setOptions({placeholder:i.placeholder??"123",ariaLabel:i.ariaLabel??"CVV",style:i.style});function m(){s.parentNode&&s.remove()}let y=t.subscribeToTeardown(m);return{frame:s,remove:()=>{y(),m()},get metadata(){return{error:o?.error??"cvvRequired",errorCode:o?.error??"cvvRequired",valid:o?.valid??!1,active:o?.focused??!1,dirty:o?.dirty??!1,touched:o?.touched??!1,submitted:!0}},addEventListener:c,addListener:c,removeListener(h,A){h!=="metadata"&&n[h].delete(A)},blur(){l.blur()},focus(){l.focus()},validate(){l.getFieldState().then(h=>{o=h,n.change.forEach(A=>A(o))})}}}}}async function Yn(r,t){R.debug("createHeadless",t);let e=await gc(r,{locale:t.locale,dialogProvider:t.dialogProvider,paymentMethodOptions:{paypal:t.sdkCore?t.paypal:void 0}}),a=await Mc(e,t.enabledPaymentMethods??[de.PAYMENT_CARD]);t.onClientSessionUpdate?.(e.configuration.clientSession),e.onClientConfigurationUpdate(async n=>{t.onClientSessionUpdate?.(n.clientSession)});let i={environment:zr?"LOCAL":e.decodedClientToken.env,primerAccountId:e.configuration.primerAccountId,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.configuration.clientSession?.clientSessionId,clientSessionToken:r,sdkVersion:t.sdkVersion};return ql({environment:zr?"LOCAL":e.decodedClientToken.env,primerAccountId:i.primerAccountId||"",checkoutSessionId:i.checkoutSessionId,clientSessionId:i.clientSessionId||"",clientSessionToken:i.clientSessionToken,sdkVersion:i.sdkVersion||"",userAgent:typeof navigator<"u"?navigator.userAgent:"unknown"}),t.onAvailablePaymentMethodsLoad?.(a.map(n=>({type:n.config.type,managerType:n.config.type===de.PAYMENT_CARD?Dr.CARD:n.config.implementationType==="NATIVE_SDK"?Dr.NATIVE:Dr.REDIRECT}))),{start:()=>Promise.resolve(),createPaymentMethodManager:async(n,o)=>{let s=a.find(({config:l})=>l.type===n);return s?s instanceof wa?tc(t,e,s,o):s instanceof Da||s instanceof xa||s instanceof Ba?ic(t,e,s):s instanceof _a?oc(t,e,s):nc(t,e,s):(R.warn(`Payment method ${n} not found`),null)},getSDKUtilities:()=>({getCardNetworkAsset:bn,getUIOrderAmount:()=>{let{merchantAmount:n,totalOrderAmount:o,currencyCode:s}=e.configuration.clientSession.order;return Gn(e.locale,n??o,s)},getCDNAssets:async n=>{let o=a.find(({config:c})=>c.type===n);if(!o)return;let{backgroundColor:s,iconUrl:l}=o.config.displayMetadata?.button||{};return{assets:{icon:l?.colored||""},colors:{background:s?.colored||"",main:s?.colored||""},description:o.config.name||null,is_primer_app:!1,name:o.config.name,website:null,goatCdnUrl:""}},getPaymentMethodConfiguration:n=>a.find(({config:o})=>o.type===n)?.config,setBillingAddress:async n=>{let{error:o,data:s}=await e.clientSessionApi.setBillingAddress(n);if(o||!s)throw o||new V({message:"Failed to set billing address"})}}),getAnalyticsUtils:()=>i,createVaultManager(){return Ec(t,e,a)},getAssetsManager:()=>({getCardNetworkAsset:bn,getPaymentMethodAsset:async n=>{let o=a.find(({config:m})=>m.type===n);if(!o)return null;let{backgroundColor:s,iconUrl:l,text:c}=o.config.displayMetadata?.button||{};return{backgroundColor:s,iconUrl:l,paymentMethodName:c,buttonText:c,displayName:o.config.name}}}),refreshClientSession:e.refreshClientConfiguration,getConfiguration:()=>e.configuration,teardown:()=>e.teardown()}}var bn=r=>{let{asset:t,display:e}=ri(r);return{cardUrl:`${Ed}/brand/card/${t}.svg`,displayName:e}},Tc=new Set(["paymentMethodType","last4Digits","network","accountNumberLastFourDigits","bankName"]);function Ut(r){let{id:t,orderId:e,paymentMethodData:a}=r,i={id:t,orderId:e};if(!a||typeof a!="object")return i;let n={};for(let[o,s]of Object.entries(a))Tc.has(o)&&(n[o]=s);return i.paymentMethodData=n,i}var Pc=new Set(["last4Digits","network","accountNumberLastFourDigits","bankName","accountType","email"]);function $n(r){let{id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i,paymentInstrumentData:n,userDescription:o}=r,s={id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i};if(o&&(s.userDescription=o),!n||typeof n!="object")return s;let l={};for(let[c,m]of Object.entries(n))Pc.has(c)&&(l[c]=m);return Object.keys(l).length>0&&(s.paymentInstrumentData=l),s}var Ft=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})}handleExternalCardSubmit(t){this.dispatchCardSubmit(t.source)}dispatchPaymentStart(){this.dispatchEvent("primer:payment-start",void 0)}dispatchPaymentSuccess(t,e){let a=Ut(t),i=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-success",{paymentSummary:a,paymentMethodType:e,timestamp:i})}dispatchPaymentFailure(t,e,a){let i=Math.floor(Date.now()/1e3),n=a?Ut(a):void 0;this.dispatchEvent("primer:payment-failure",{error:t,paymentSummary:n,paymentMethodType:e,timestamp:i})}dispatchVaultMethodsUpdate(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault:methods-update",{vaultedPayments:t,timestamp:e})}dispatchVaultSubmit(t){this.dispatchEvent("primer:vault-submit",{source:t})}handleExternalVaultSubmit(t){this.dispatchVaultSubmit(t.source)}dispatchShowOtherPaymentsToggle(t,e){this.dispatchEvent("primer:show-other-payments-toggle",{action:t,source:e})}handleExternalShowOtherPaymentsToggle(t){this.dispatchShowOtherPaymentsToggle(t.action,t.source)}};var pt=class extends Event{constructor(t,e,a,i){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=a,this.subscribe=i??!1}};var Ht=class{constructor(t,e,a,i){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(n,o)=>{this.unsubscribe&&(this.unsubscribe!==o&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=n,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(n,o)),this.unsubscribe=o},this.host=t,e.context!==void 0){let n=e;this.context=n.context,this.callback=n.callback,this.subscribe=n.subscribe??!1}else this.context=e,this.callback=a,this.subscribe=i??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new pt(this.context,this.host,this.t,this.subscribe))}};var Ka=class{get value(){return this.o}set value(t){this.setValue(t)}setValue(t,e=!1){let a=e||!Object.is(t,this.o);this.o=t,a&&this.updateObservers()}constructor(t){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:a}]of this.subscriptions)e(this.o,a)},t!==void 0&&(this.value=t)}addCallback(t,e,a){if(!a)return void t(this.value);this.subscriptions.has(t)||this.subscriptions.set(t,{disposer:()=>{this.subscriptions.delete(t)},consumerHost:e});let{disposer:i}=this.subscriptions.get(t);t(this.value,i)}clearCallbacks(){this.subscriptions.clear()}};var di=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},$=class extends Ka{constructor(t,e,a){super(e.context!==void 0?e.initialValue:a),this.onContextRequest=i=>{if(i.context!==this.context)return;let n=i.contextTarget??i.composedPath()[0];n!==this.host&&(i.stopPropagation(),this.addCallback(i.callback,n,i.subscribe))},this.onProviderRequest=i=>{if(i.context!==this.context||(i.contextTarget??i.composedPath()[0])===this.host)return;let n=new Set;for(let[o,{consumerHost:s}]of this.subscriptions)n.has(o)||(n.add(o),s.dispatchEvent(new pt(this.context,s,o,!0)));i.stopPropagation()},this.host=t,e.context!==void 0?this.context=e.context:this.context=e,this.attachListeners(),this.host.addController?.(this)}attachListeners(){this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onProviderRequest)}hostConnected(){this.host.dispatchEvent(new di(this.context,this.host))}};function M({context:r,subscribe:t}){return(e,a)=>{typeof a=="object"?a.addInitializer((function(){new Ht(this,{context:r,callback:i=>{e.set.call(this,i)},subscribe:t})})):e.constructor.addInitializer((i=>{new Ht(i,{context:r,callback:n=>{i[a]=n},subscribe:t})}))}}var mt=Symbol("analytics-context");var Ge=Symbol("events-context");var Va="cardNetworksContext";var he="clientOptionsContext";var Yt="computedStylesContext";var Y="headlessInstanceContext";var Ua="configuration";var Fa="klarnaCategoriesContext";var z="managerContext";var ht="paymentMethodsContext";var j="sdkStateContext";var ge="vaultManagerContext";var Ke="vaultManagerCvvContext";function kc(r,t,e,a){let i=r,n=e;return{dispatch:o=>{let s=i,l=t(i,o,n);zn(s,l)?i=l:(i=l,a(l))},getState:()=>Object.freeze({...i}),setCallbacks:o=>{n={...n,...o}}}}function zn(r,t){if(r===t)return!0;if(r==null||t==null||typeof r!="object"||typeof t!="object")return!1;let e=Object.keys(r),a=Object.keys(t);if(e.length!==a.length)return!1;for(let i of e){if(!a.includes(i))return!1;let n=r[i],o=t[i];if(typeof n=="object"&&typeof o=="object"){if(!zn(n,o))return!1}else if(n!==o)return!1}return!0}function ci(r){return(t,e,a)=>{let i=r[e.type];if(!i)throw new Error(`No handler for action type: ${e.type}`);return i(t,e,a)}}var Et=class{constructor(t,e,a,i,n=()=>{this.host.requestUpdate()}){this.host=t;this.stateHandler=n;this.host.addController(this),this._dispatcher=kc(e,a,i,o=>{this.stateHandler(o)})}get currentState(){return this._dispatcher.getState()}dispatch(t){this._dispatcher.dispatch(t)}setCallbacks(t){this._dispatcher.setCallbacks(t)}hostConnected(){}hostDisconnected(){}},Ha=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 jn={isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null},Wn=jn;function Nc(r,t){switch(t.type){case"SET_LOADING":return{...r,isLoading:t.payload};case"SET_PROCESSING":return{...r,isProcessing:t.payload,...t.payload&&{primerJsError:null,paymentFailure:null}};case"SET_SUCCESS":return{...r,isSuccessful:t.payload};case"SET_PRIMER_JS_ERROR":return{...r,primerJsError:t.payload};case"SET_PAYMENT_FAILURE":return{...r,isProcessing:!1,paymentFailure:t.payload};case"COMPLETE_PROCESSING":return{...r,isProcessing:!1,isSuccessful:!0};case"RESET":return{isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null};default:return r}}var Ya=class extends Et{constructor(t){super(t,jn,Nc,null,e=>{t.sdkContextController.setSdkState(e),t.primerEventsController.dispatchSdkState(e)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setProcessing(t){this.dispatch({type:"SET_PROCESSING",payload:t})}setSuccess(t){this.dispatch({type:"SET_SUCCESS",payload:t})}setPrimerJsError(t){this.dispatch({type:"SET_PRIMER_JS_ERROR",payload:t})}setPaymentFailure(t){this.dispatch({type:"SET_PAYMENT_FAILURE",payload:t})}completeProcessing(){this.dispatch({type:"COMPLETE_PROCESSING"})}reset(){this.dispatch({type:"RESET"})}startLoading(){this.setLoading(!0)}completeLoading(){this.setLoading(!1)}startProcessing(){this.setProcessing(!0)}stopProcessing(){this.setProcessing(!1)}resetError(){this.setPrimerJsError(null),this.setPaymentFailure(null)}forceCompleteLoading(){this.setLoading(!1)}};var $a=class{constructor(t){this.sdkStateProvider=null;this.paymentMethodsProvider=null;this.paymentManagerProvider=null;this.cardNetworksContext=null;this.vaultManagerCvvProvider=null;this.clientOptionsContext=null;this.headlessUtilsProvider=null;this.configurationProvider=null;this.klarnaCategoriesProvider=null;this.computedStylesProvider=null;this.analyticsProvider=null;this.eventsProvider=null;(this.host=t).addController(this),this.sdkStateProvider=new $(t,{context:j,initialValue:Wn}),this.paymentMethodsProvider=new $(t,{context:ht,initialValue:null}),this.paymentManagerProvider=new $(t,{context:z,initialValue:new Map}),this.cardNetworksContext=new $(t,{context:Va,initialValue:null}),this.vaultManagerProvider=new $(t,{context:ge,initialValue:null}),this.vaultManagerCvvProvider=new $(t,{context:Ke,initialValue:null}),this.clientOptionsContext=new $(t,{context:he,initialValue:null}),this.klarnaCategoriesProvider=new $(t,{context:Fa,initialValue:{categories:[],isLoading:!0}}),this.headlessUtilsProvider=new $(t,{context:Y,initialValue:null}),this.configurationProvider=new $(t,{context:Ua,initialValue:null}),this.computedStylesProvider=new $(t,{context:Yt,initialValue:null}),this.analyticsProvider=new $(t,{context:mt,initialValue:null}),this.eventsProvider=new $(t,{context:Ge,initialValue:null})}hostConnected(){}setSdkState(t){this.sdkStateProvider?.setValue(t)}setPaymentMethods(t){this.paymentMethodsProvider?.setValue(t)}setPaymentManagers(t){this.paymentManagerProvider?.setValue(t)}setCardNetworks(t){this.cardNetworksContext?.setValue(t)}setVaultManager(t){this.vaultManagerProvider?.setValue(t)}setKlarnaCategories(t){this.klarnaCategoriesProvider?.setValue(t)}setClientOptions(t){this.clientOptionsContext?.setValue(t)}setHeadlessUtils(t){this.headlessUtilsProvider?.setValue(t)}setConfiguration(t){this.configurationProvider?.setValue(t)}setAnalyticsUtils(t){this.analyticsProvider?.setValue(t)}getAnalyticsUtils(){return this.analyticsProvider?.value}setComputedStyles(t){this.computedStylesProvider?.setValue(t)}setVaultManagerCvv(t){this.vaultManagerCvvProvider?.setValue(t)}setEventsController(t){this.eventsProvider?.setValue(t)}};var ui=class{constructor(){x(this,"context",null)}initialize(t){this.context=t,E.debug("Session context initialized:",{checkoutSessionId:t.checkoutSessionId,clientSessionId:t.clientSessionId,primerAccountId:t.primerAccountId,environment:t.environment})}getContext(){return this.context}clear(){E.debug("Session context cleared"),this.context=null}isInitialized(){return this.context!==null}},$t=new ui;var Ic={LOCAL:"https://analytics.dev.data.primer.io/v1/sdk-logs",DEV:"https://analytics.dev.data.primer.io/v1/sdk-logs",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-logs",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-logs",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-logs"};function Jn(r,t){let e=$t.getContext(),i={message:r instanceof Error?r.message:typeof r=="string"?r:JSON.stringify(r)};r instanceof Error&&r.stack&&(i.stack=r.stack),e?(i.checkoutSessionId=e.checkoutSessionId,i.clientSessionId=e.clientSessionId,i.primerAccountId=e.primerAccountId,i.userAgent=e.userAgent):(t?.checkoutSessionId&&(i.checkoutSessionId=t.checkoutSessionId),t?.clientSessionId&&(i.clientSessionId=t.clientSessionId),t?.primerAccountId&&(i.primerAccountId=t.primerAccountId),t?.userAgent&&(i.userAgent=t.userAgent)),t?.metadata&&Object.assign(i,t.metadata),t.status&&Object.assign(i,{status:t.status});let n={message:JSON.stringify(i),hostname:typeof window<"u"?window.location.hostname:"unknown",service:"web-sdk",ddsource:"lambda",ddtags:`env:${e?.environment||t?.environment},version:${e?.sdkVersion||t?.sdkVersion}`};Lc(n,{environment:e?.environment||t?.environment,clientSessionToken:e?.clientSessionToken||t?.clientSessionToken})}function Lc(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){E.debug("\u{1F436}\u{1F436}\u{1F436} [Datadog Log] \u{1F436}\u{1F436}\u{1F436}",r);return}let a=Ic[t||"LOCAL"];if(!a){E.warn("No logging endpoint configured for current environment");return}fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{E.error("Failed to send log event:",i)})}var K=class K{static log(t,...e){K.enabled}static info(t,...e){K.enabled}static warn(t,...e){K.enabled}static error(t,...e){K.enabled&&e.forEach(a=>{a instanceof Error&&a.toJSON})}static errorWithDatadog(t,e){let{error:a,status:i="error"}=e||{};if(K.enabled){a instanceof Error&&a.toJSON;try{let n=a||t,o={status:i,metadata:{sdkOptions:K.sdkOptions,clientToken:K.clientToken}};Jn(n,o)}catch{K.enabled}}}static debug(t,...e){K.enabled}static table(t,e){K.enabled}static time(t){K.enabled}static timeEnd(t){K.enabled}static setSdkOptions(t){K.sdkOptions=t}static setClientToken(t){K.clientToken=t}};x(K,"enabled",!0),x(K,"sdkOptions"),x(K,"clientToken"),x(K,"defaultFont","font-family: Consolas, monospace; font-size: 12px;"),x(K,"brandTag","[PRIMER]"),x(K,"brandStyle",`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${K.defaultFont}`),x(K,"styles",{log:`color: #4CAF50; ${K.defaultFont}`,info:`color: #2196F3; ${K.defaultFont}`,warn:`color: #FF9800; ${K.defaultFont}`,error:`color: #F44336; ${K.defaultFont}`,debug:`color: #9C27B0; ${K.defaultFont}`});var E=K;var Tt=class Tt{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){E.error("Error parsing customStyles property.",e instanceof Error?e:new Error(String(e)))}}isValidCssProperty(t){return/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)}isValidCssValue(t){let a=/^[\w\s#.,%()\-+/!]+$/.test(t);return a||E.warn(`Rejected potentially unsafe CSS value: ${t}`),a}getCssVarName(t){let e=Tt.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(a,i)=>`-${i.toLowerCase()}`)}`,Tt.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let a of Object.keys(t)){let i=t[a];if(!i)continue;if(!this.isValidCssProperty(a)){E.warn(`Skipping invalid CSS property name: ${a}`);continue}if(!this.isValidCssValue(i))continue;let n=this.getCssVarName(a);e.push([n,i])}if(e.length>0)for(let[a,i]of e)this.host.style.setProperty(a,i)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of Tt.cssVarCache.keys()){let e=Tt.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};Tt.cssVarCache=new Map;var za=Tt;var ja=globalThis,Ja=ja.ShadowRoot&&(ja.ShadyCSS===void 0||ja.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,qn=Symbol(),Zn=new WeakMap,Wa=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==qn)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(Ja&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=Zn.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&Zn.set(e,t))}return t}toString(){return this.cssText}},Qn=r=>new Wa(typeof r=="string"?r:r+"",void 0,qn);var pi=(r,t)=>{if(Ja)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=ja.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},Za=Ja?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return Qn(e)})(r):r;var{is:Rc,defineProperty:xc,getOwnPropertyDescriptor:_c,getOwnPropertyNames:wc,getOwnPropertySymbols:Bc,getPrototypeOf:Dc}=Object,gt=globalThis,Xn=gt.trustedTypes,Oc=Xn?Xn.emptyScript:"",Gc=gt.reactiveElementPolyfillSupport,ra=(r,t)=>r,mi={toAttribute(r,t){switch(t){case Boolean:r=r?Oc:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},qa=(r,t)=>!Rc(r,t),eo={attribute:!0,type:String,converter:mi,reflect:!1,hasChanged:qa};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),gt.litPropertyMetadata??(gt.litPropertyMetadata=new WeakMap);var Pt=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=eo){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let a=Symbol(),i=this.getPropertyDescriptor(t,a,e);i!==void 0&&xc(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=_c(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get(){return i?.call(this)},set(o){let s=i?.call(this);n.call(this,o),this.requestUpdate(t,s,a)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??eo}static _$Ei(){if(this.hasOwnProperty(ra("elementProperties")))return;let t=Dc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(ra("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ra("properties"))){let e=this.properties,a=[...wc(e),...Bc(e)];for(let i of a)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[a,i]of e)this.elementProperties.set(a,i)}this._$Eh=new Map;for(let[e,a]of this.elementProperties){let i=this._$Eu(e,a);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let a=new Set(t.flat(1/0).reverse());for(let i of a)e.unshift(Za(i))}else t!==void 0&&e.push(Za(t));return e}static _$Eu(t,e){let a=e.attribute;return a===!1?void 0:typeof a=="string"?a:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let a of e.keys())this.hasOwnProperty(a)&&(t.set(a,this[a]),delete this[a]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return pi(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,a){this._$AK(t,a)}_$EC(t,e){let a=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,a);if(i!==void 0&&a.reflect===!0){let n=(a.converter?.toAttribute!==void 0?a.converter:mi).toAttribute(e,a.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let a=this.constructor,i=a._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=a.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:mi;this._$Em=i,this[i]=o.fromAttribute(e,n.type),this._$Em=null}}requestUpdate(t,e,a){if(t!==void 0){if(a??(a=this.constructor.getPropertyOptions(t)),!(a.hasChanged??qa)(this[t],e))return;this.P(t,e,a)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,e,a){this._$AL.has(t)||this._$AL.set(t,e),a.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let a=this.constructor.elementProperties;if(a.size>0)for(let[i,n]of a)n.wrapped!==!0||this._$AL.has(i)||this[i]===void 0||this.P(i,this[i],n)}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((a=>a.hostUpdate?.())),this.update(e)):this._$EU()}catch(a){throw t=!1,this._$EU(),a}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach((e=>this._$EC(e,this[e])))),this._$EU()}updated(t){}firstUpdated(t){}};Pt.elementStyles=[],Pt.shadowRootOptions={mode:"open"},Pt[ra("elementProperties")]=new Map,Pt[ra("finalized")]=new Map,Gc?.({ReactiveElement:Pt}),(gt.reactiveElementVersions??(gt.reactiveElementVersions=[])).push("2.0.4");var yt={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},_=Symbol(),D=class{get taskComplete(){return this.t||(this.i===1?this.t=new Promise(((t,e)=>{this.o=t,this.h=e})):this.i===3?this.t=Promise.reject(this.l):this.t=Promise.resolve(this.u)),this.t}constructor(t,e,a){this.p=0,this.i=0,(this._=t).addController(this);let i=typeof e=="object"?e:{task:e,args:a};this.v=i.task,this.j=i.args,this.m=i.argsEqual??to,this.k=i.onComplete,this.A=i.onError,this.autoRun=i.autoRun??!0,"initialValue"in i&&(this.u=i.initialValue,this.i=2,this.O=this.T?.())}hostUpdate(){this.autoRun===!0&&this.S()}hostUpdated(){this.autoRun==="afterUpdate"&&this.S()}T(){if(this.j===void 0)return;let t=this.j();if(!Array.isArray(t))throw Error("The args function must return an array");return t}async S(){let t=this.T(),e=this.O;this.O=t,t===e||t===void 0||e!==void 0&&this.m(e,t)||await this.run(t)}async run(t){let e,a;t??(t=this.T()),this.O=t,this.i===1?this.q?.abort():(this.t=void 0,this.o=void 0,this.h=void 0),this.i=1,this.autoRun==="afterUpdate"?queueMicrotask((()=>this._.requestUpdate())):this._.requestUpdate();let i=++this.p;this.q=new AbortController;let n=!1;try{e=await this.v(t,{signal:this.q.signal})}catch(o){n=!0,a=o}if(this.p===i){if(e===_)this.i=0;else{if(n===!1){try{this.k?.(e)}catch{}this.i=2,this.o?.(e)}else{try{this.A?.(a)}catch{}this.i=3,this.h?.(a)}this.u=e,this.l=a}this._.requestUpdate()}}abort(t){this.i===1&&this.q?.abort(t)}get value(){return this.u}get error(){return this.l}get status(){return this.i}render(t){switch(this.i){case 0:return t.initial?.();case 1:return t.pending?.();case 2:return t.complete?.(this.value);case 3:return t.error?.(this.error);default:throw Error("Unexpected status: "+this.i)}}},to=(r,t)=>r===t||r.length===t.length&&r.every(((e,a)=>!qa(e,t[a])));var Qa=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}},Xa=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 Kc={SET_LOADING:(r,t)=>({...r,isLoading:t.payload}),SET_UPDATING:(r,t)=>({...r,isUpdating:t.payload}),INITIALIZE_VAULT_MANAGER:(r,t,e)=>({...r,enabled:t.vaultEnabled,cvvRecapture:t.cvvRecapture,showEmptyState:t.showEmptyState,deleteVaultedPaymentMethod:e.deleteVaultedPaymentMethod,startVaultedPaymentFlow:e.startVaultedPaymentFlow,createCvvInput:e.createCvvInput}),UPDATE_PAYMENT_METHODS:(r,t)=>({...r,vaultedPaymentMethods:t.payload,isLoading:!1,isUpdating:!1}),SET_ERROR:r=>({...r,isLoading:!1,isUpdating:!1}),DISABLE:r=>({...r,enabled:!1}),RESET:()=>ao},Vc={INITIALIZE_CVV:(r,t,e)=>({...r,setCvvInput:e.setCvvInput,setSelectedVaultedPaymentMethod:e.setSelectedVaultedPaymentMethod}),SET_FORM_DIRTY:(r,t)=>({...r,formIsDirty:t.payload}),SET_CVV_INPUT:(r,t)=>({...r,cvvInput:t.payload}),SET_SELECTED_VAULTED_PAYMENT_METHOD:(r,t)=>({...r,selectedVaultedPaymentMethod:t.payload}),RESET_CVV:()=>ro},Uc=ci(Kc),Fc=ci(Vc),ao={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!0,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},ro={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},hi=class extends Et{constructor(t,e){super(t,ao,Uc,e,a=>{t.sdkContextController.setVaultManager(a)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setUpdating(t){this.dispatch({type:"SET_UPDATING",payload:t})}initializeVaultManager(t,e,a,i){this.dispatch({type:"INITIALIZE_VAULT_MANAGER",payload:t,vaultEnabled:e,cvvRecapture:a,showEmptyState:i})}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"})}},gi=class extends Et{constructor(t,e){super(t,ro,Fc,e,a=>{t.sdkContextController.setVaultManagerCvv(a)})}initializeCvv(t){this.dispatch({type:"INITIALIZE_CVV",createCvvInput:t})}setFormDirty(t){this.dispatch({type:"SET_FORM_DIRTY",payload:t})}setCvvInputState(t){this.dispatch({type:"SET_CVV_INPUT",payload:t})}setSelectedPaymentMethod(t){this.dispatch({type:"SET_SELECTED_VAULTED_PAYMENT_METHOD",payload:t})}resetCvv(){this.dispatch({type:"RESET_CVV"})}},ia=class extends Ha{constructor(e){super(e);this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(e)};this.deleteVaultedPaymentMethod=async e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.coreController.updatePaymentMethods(this.vaultManagerState.vaultedPaymentMethods),await this._vaultManager.deleteVaultedPaymentMethod(e),await this.fetchVaultedPaymentMethods()}catch(a){let i=a instanceof Error?a:new Error("Failed to delete payment method");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}};this.setCvvInput=e=>{this.itemController.setCvvInputState(e)};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let e=this.vaultItemState.selectedVaultedPaymentMethod,a=this.vaultManagerState.cvvRecapture,i=this.vaultItemState.cvvInput;if(!e||a&&(!i||i.metadata.error)){this.itemController.setFormDirty(!0);return}this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e.id,a?{cvv:i.valueToken}:void 0)}catch(n){E.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:n});let o=n instanceof Error?n:new Error("Failed to start vaulted payment flow");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o),this.host.sdkStateController.stopProcessing()}};this.setSelectedVaultedPaymentMethod=e=>{this.itemController.setSelectedPaymentMethod(e),this.itemController.setFormDirty(!1)};this.coreController=new hi(e,{deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.itemController=new gi(e,{setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)}),this.addController(this.coreController),this.addController(this.itemController),new D(this.host,{task:async([a,i])=>{if(!a||!i?.vaultEnabled)return this.coreController.disable(),_;this.coreController.setLoading(!0);try{let n=a();this._vaultManager=n,this.coreController.initializeVaultManager(n,i.vaultEnabled,!!i.captureVaultedCardCvv,i.showEmptyState??!0),this.itemController.initializeCvv(n.createCvvInput),await this.fetchVaultedPaymentMethods(!0),E.log("VaultManagerController: Vault initialized successfully",{coreState:this.coreController.currentState,cvvState:this.itemController.currentState})}catch(n){E.errorWithDatadog("VaultManagerController: Failed to initialize vault",{error:n});let o=n instanceof Error?n:new Error("Unknown error");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o)}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}initializeVaultManager(e,a){this.createVaultManagerFn=e,this.options=a??null}get vaultManager(){return this._vaultManager}set vaultManager(e){this._vaultManager=e,this.host.requestUpdate()}get options(){return this._options}set options(e){this._options=e,this.host.requestUpdate()}get vaultManagerState(){return this.coreController.currentState}get vaultItemState(){return this.itemController.currentState}hostDisconnected(){super.hostDisconnected(),this.vaultManager=null,this.coreController.reset()}createVaultedPaymentsWrapper(e){let a=new Map;for(let i of e){let n=$n(i);a.set(n.id,n)}return new Xa(a)}updatePaymentMethodsWithEvents(e){this.coreController.updatePaymentMethods(e);let a=this.createVaultedPaymentsWrapper(e);this.host.primerEventsController.dispatchVaultMethodsUpdate(a),this.host.primerJS?.handleVaultedMethodsUpdate(a),E.log("VaultManagerController: Dispatched vault methods update",{methodCount:e.length,filteredMethodCount:a.size()})}async fetchVaultedPaymentMethods(e){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{e||this.coreController.setUpdating(!0);let a=await this._vaultManager.fetchVaultedPaymentMethods();return E.log("VaultManagerController: Fetched payment methods",a),this.updatePaymentMethodsWithEvents(a),a}catch(a){let i=a instanceof Error?a:new Error("Failed to fetch payment methods");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}}};var io=()=>no.randomUUID?.()||Hc(),Hc=()=>("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,r=>(r^Yc()>>r/4).toString(16)),Yc=()=>(no.getRandomValues?.(new Uint8Array(1))[0]??Math.random()*16)&15,no=typeof crypto<"u"?crypto:{};var $c={LOCAL:"",DEV:"https://analytics.dev.data.primer.io/v1/sdk-analytic-events",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-analytic-events",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-analytic-events"},yi=class{sendEvent(t){let e=$t.getContext();if(!e){E.error("Session context not initialized. Call initializeAnalytics() first.");return}let a={id:io(),timestamp:Math.floor(Date.now()/1e3),sdkType:"WEB",eventName:t.eventName,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.clientSessionId,primerAccountId:e.primerAccountId,sdkVersion:e.sdkVersion,userAgent:e.userAgent,eventType:t.eventType,userLocale:t.userLocale,paymentMethod:t.paymentMethod,paymentId:t.paymentId,redirectDestinationUrl:t.redirectDestinationUrl,threedsProvider:t.threedsProvider,threedsResponse:t.threedsResponse};jc(a,e)}},zc=new yi;function oo(r){let t={...r,userAgent:r.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};$t.initialize(t)}function Q(r){zc.sendEvent(r)}function so(){$t.clear()}async function jc(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){E.debug(`Analytics event ${r.eventName}:`,r);return}let a=$c[t];return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{E.error("Failed to send analytics event:",i)})}var na="lit-localize-status";var lo=r=>typeof r!="string"&&"strTag"in r,er=(r,t,e)=>{let a=r[0];for(let i=1;i<r.length;i++)a+=t[e?e[i-1]:i-1],a+=r[i];return a};var oa=(r=>lo(r)?er(r.strings,r.values):r);var b=oa,co=!1;function fi(r){if(co)throw new Error("lit-localize can only be configured once");b=r,co=!0}var vi=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(na,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(na,this.__litLocalizeEventHandler)}},Wc=r=>r.addController(new vi(r)),uo=Wc;var B=()=>(r,t)=>(r.addInitializer(uo),r);var sa=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 Xe=[];for(let r=0;r<256;r++)Xe[r]=(r>>4&15).toString(16)+(r&15).toString(16);function po(r){let t=0,e=8997,a=0,i=33826,n=0,o=40164,s=0,l=52210;for(let c=0;c<r.length;c++)e^=r.charCodeAt(c),t=e*435,a=i*435,n=o*435,s=l*435,n+=e<<8,s+=i<<8,a+=t>>>16,e=t&65535,n+=a>>>16,i=a&65535,l=s+(n>>>16)&65535,o=n&65535;return Xe[l>>8]+Xe[l&255]+Xe[o>>8]+Xe[o&255]+Xe[i>>8]+Xe[i&255]+Xe[e>>8]+Xe[e&255]}var Jc="",Zc="h",qc="s";function mo(r,t){return(t?Zc:qc)+po(typeof r=="string"?r:r.join(Jc))}var ho=new WeakMap,go=new Map;function yo(r,t,e){if(r){let a=e?.id??Qc(t),i=r[a];if(i){if(typeof i=="string")return i;if("strTag"in i)return er(i.strings,t.values,i.values);{let n=ho.get(i);return n===void 0&&(n=i.values,ho.set(i,n)),{...i,values:n.map(o=>t.values[o])}}}}return oa(t)}function Qc(r){let t=typeof r=="string"?r:r.strings,e=go.get(t);return e===void 0&&(e=mo(t,typeof r!="string"&&!("strTag"in r)),go.set(t,e)),e}function Si(r){window.dispatchEvent(new CustomEvent(na,{detail:r}))}var ar="",bi,fo,rr,Ci,vo,kt=new sa;kt.resolve();var tr=0,So=r=>(fi(((t,e)=>yo(vo,t,e))),ar=fo=r.sourceLocale,rr=new Set(r.targetLocales),rr.add(r.sourceLocale),Ci=r.loadLocale,{getLocale:Xc,setLocale:eu}),Xc=()=>ar,eu=r=>{if(r===(bi??ar))return kt.promise;if(!rr||!Ci)throw new Error("Internal error");if(!rr.has(r))throw new Error("Invalid locale code");tr++;let t=tr;return bi=r,kt.settled&&(kt=new sa),Si({status:"loading",loadingLocale:r}),(r===fo?Promise.resolve({templates:void 0}):Ci(r)).then(a=>{tr===t&&(ar=r,bi=void 0,vo=a.templates,Si({status:"ready",readyLocale:r}),kt.resolve())},a=>{tr===t&&(Si({status:"error",errorLocale:r,errorMessage:a.toString()}),kt.reject(a))}),kt.promise};var Ai="en",Mi=["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"],Ei="You must call `loadLocale` first to set up the localized template.",ir,nr,bo=r=>{let t=So({sourceLocale:Ai,targetLocales:Mi,loadLocale:r});ir=t.getLocale,nr=t.setLocale};var Ti=r=>{bo(r)},Pi=r=>{if(!nr)throw new Error(Ei);return nr(r)},ki=()=>{if(!ir)throw new Error(Ei);return ir()};var la=new Set(Mi);la.add(Ai);var Ni=r=>{if(typeof r!="string")return!1;if(r==="en")return!0;let t=r.replace("_","-");if(la.has(t))return!0;let e=t.split("-")[0];return!!la.has(e)},Ii=r=>{if(r==="en")return"en-GB";let t=r.replace("_","-");if(la.has(t))return t;let e=t.split("-")[0];return la.has(e)?e:"en-GB"};var or=globalThis,sr=or.ShadowRoot&&(or.ShadyCSS===void 0||or.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Li=Symbol(),Co=new WeakMap,da=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==Li)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(sr&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=Co.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&Co.set(e,t))}return t}toString(){return this.cssText}},ye=r=>new da(typeof r=="string"?r:r+"",void 0,Li),f=(r,...t)=>{let e=r.length===1?r[0]:t.reduce(((a,i,n)=>a+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[n+1]),r[0]);return new da(e,r,Li)},Ao=(r,t)=>{if(sr)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=or.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},Ri=sr?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return ye(e)})(r):r;var{is:tu,defineProperty:au,getOwnPropertyDescriptor:ru,getOwnPropertyNames:iu,getOwnPropertySymbols:nu,getPrototypeOf:ou}=Object,ft=globalThis,Mo=ft.trustedTypes,su=Mo?Mo.emptyScript:"",lu=ft.reactiveElementPolyfillSupport,ca=(r,t)=>r,ua={toAttribute(r,t){switch(t){case Boolean:r=r?su:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},lr=(r,t)=>!tu(r,t),Eo={attribute:!0,type:String,converter:ua,reflect:!1,useDefault:!1,hasChanged:lr};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ft.litPropertyMetadata??(ft.litPropertyMetadata=new WeakMap);var et=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=Eo){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let a=Symbol(),i=this.getPropertyDescriptor(t,a,e);i!==void 0&&au(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=ru(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get:i,set(o){let s=i?.call(this);n?.call(this,o),this.requestUpdate(t,s,a)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Eo}static _$Ei(){if(this.hasOwnProperty(ca("elementProperties")))return;let t=ou(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(ca("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ca("properties"))){let e=this.properties,a=[...iu(e),...nu(e)];for(let i of a)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[a,i]of e)this.elementProperties.set(a,i)}this._$Eh=new Map;for(let[e,a]of this.elementProperties){let i=this._$Eu(e,a);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let a=new Set(t.flat(1/0).reverse());for(let i of a)e.unshift(Ri(i))}else t!==void 0&&e.push(Ri(t));return e}static _$Eu(t,e){let a=e.attribute;return a===!1?void 0:typeof a=="string"?a:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let a of e.keys())this.hasOwnProperty(a)&&(t.set(a,this[a]),delete this[a]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Ao(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,a){this._$AK(t,a)}_$ET(t,e){let a=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,a);if(i!==void 0&&a.reflect===!0){let n=(a.converter?.toAttribute!==void 0?a.converter:ua).toAttribute(e,a.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let a=this.constructor,i=a._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=a.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:ua;this._$Em=i,this[i]=o.fromAttribute(e,n.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(t,e,a){if(t!==void 0){let i=this.constructor,n=this[t];if(a??(a=i.getPropertyOptions(t)),!((a.hasChanged??lr)(n,e)||a.useDefault&&a.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,a))))return;this.C(t,e,a)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:a,reflect:i,wrapped:n},o){a&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,o??e??this[t]),n!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||a||(e=void 0),this._$AL.set(t,e)),i===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let a=this.constructor.elementProperties;if(a.size>0)for(let[i,n]of a){let{wrapped:o}=n,s=this[i];o!==!0||this._$AL.has(i)||s===void 0||this.C(i,void 0,n,s)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((a=>a.hostUpdate?.())),this.update(e)):this._$EM()}catch(a){throw t=!1,this._$EM(),a}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(t){}firstUpdated(t){}};et.elementStyles=[],et.shadowRootOptions={mode:"open"},et[ca("elementProperties")]=new Map,et[ca("finalized")]=new Map,lu?.({ReactiveElement:et}),(ft.reactiveElementVersions??(ft.reactiveElementVersions=[])).push("2.1.0");var ma=globalThis,dr=ma.trustedTypes,To=dr?dr.createPolicy("lit-html",{createHTML:r=>r}):void 0,_i="$lit$",tt=`lit$${Math.random().toFixed(9).slice(2)}$`,wi="?"+tt,du=`<${wi}>`,Lt=document,ha=()=>Lt.createComment(""),ga=r=>r===null||typeof r!="object"&&typeof r!="function",Bi=Array.isArray,Ro=r=>Bi(r)||typeof r?.[Symbol.iterator]=="function",xi=`[
151
+ `;async function Mc(r,t){let e=r.configuration.paymentMethods.map(i=>{if(!t.includes(i.type))return null;if(R.debug("Initializing payment method:",i.type),i.implementationType==="WEB_REDIRECT")return new Xr(i,r);if(i.type===de.PAYMENT_CARD)return new wa(i,r);if(i.type===de.PAYPAL)return new Da(i,r);if(i.type===de.APPLE_PAY)return new xa(i,r);if(i.type===de.GOOGLE_PAY)return new Ba(i,r);if(i.type===de.ADYEN_BLIK)return new _a(i,r)}).map(async i=>{if(!i)return null;try{return await i.setup()?i:null}catch(n){return R.warn(`Failed to initialize payment method ${i.config.type}:`,n),null}});return(await Promise.all(e)).filter(i=>!!i)}function Ec(r,t,e){if(!t.configuration.clientSession.customer?.customerId)throw new V({message:"You must provide a `customerId` in the client session to use the Vault Manager."});let a=[];return{async fetchVaultedPaymentMethods(){let{data:i,error:n}=await t.pciApi.getPaymentInstruments();if(n)throw n;if(!i)throw new V({code:Ta.VAULT_ERROR,message:"Missing vaulted payment methods data"});return a=i.data,a},async deleteVaultedPaymentMethod(i){if(!a.find(s=>s.id===i))throw new V({code:Ta.VAULT_ERROR,message:"deleteVaultedPaymentMethod: the id provided doesn't match any vaulted payment method"});let{error:o}=await t.pciApi.deletePaymentInstrument(i);if(o)throw o;a=a.filter(s=>s.id!==i)},async startPaymentFlow(i){let n=a.find(s=>s.id===i);if(!n)throw new V({code:Ta.VAULT_ERROR,message:"startPaymentFlow: the id provided doesn't match any vaulted payment method"});let o=e.find(s=>s.config.type===n.paymentMethodType);if(!o)throw new V({code:Ta.TOKENIZATION_ERROR,message:`Payment instrument type ${n.paymentInstrumentType} is not recognized or not supported.`});await Ga(r,o,n)},async createCvvInput(i){let n={blur:new Set,change:new Set,focus:new Set},o,s=Xt(t.checkoutSessionId,cn);await new Promise(h=>{s.onload=()=>{h()},(typeof i.container=="string"?document.querySelector(i.container):i.container)?.appendChild(s)}),Wr(s,i.style),s.setAttribute("title",i.ariaLabel||"");let l=li({namespace:`${t.checkoutSessionId}-${cn}`,onMessage:h=>{let A=C=>h(C.data);return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},sendMessage:h=>{s.contentWindow.postMessage(h,"*")}});function c(h,A){h!=="metadata"&&n[h].add(A)}l.setOnFocus(()=>{n.focus.forEach(h=>h())}),l.setOnBlur(()=>{n.blur.forEach(h=>h())}),l.setOnInput(h=>{o=h,n.change.forEach(A=>A())}),l.setCardNetwork(i.cardNetwork??""),l.setOptions({placeholder:i.placeholder??"123",ariaLabel:i.ariaLabel??"CVV",style:i.style});function m(){s.parentNode&&s.remove()}let y=t.subscribeToTeardown(m);return{frame:s,remove:()=>{y(),m()},get metadata(){return{error:o?.error??"cvvRequired",errorCode:o?.error??"cvvRequired",valid:o?.valid??!1,active:o?.focused??!1,dirty:o?.dirty??!1,touched:o?.touched??!1,submitted:!0}},addEventListener:c,addListener:c,removeListener(h,A){h!=="metadata"&&n[h].delete(A)},blur(){l.blur()},focus(){l.focus()},validate(){l.getFieldState().then(h=>{o=h,n.change.forEach(A=>A(o))})}}}}}async function Yn(r,t){R.debug("createHeadless",t);let e=await gc(r,{locale:t.locale,dialogProvider:t.dialogProvider,paymentMethodOptions:{paypal:t.sdkCore?t.paypal:void 0}}),a=await Mc(e,t.enabledPaymentMethods??[de.PAYMENT_CARD]);t.onClientSessionUpdate?.(e.configuration.clientSession),e.onClientConfigurationUpdate(async n=>{t.onClientSessionUpdate?.(n.clientSession)});let i={environment:zr?"LOCAL":e.decodedClientToken.env,primerAccountId:e.configuration.primerAccountId,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.configuration.clientSession?.clientSessionId,clientSessionToken:r,sdkVersion:t.sdkVersion};return ql({environment:zr?"LOCAL":e.decodedClientToken.env,primerAccountId:i.primerAccountId||"",checkoutSessionId:i.checkoutSessionId,clientSessionId:i.clientSessionId||"",clientSessionToken:i.clientSessionToken,sdkVersion:i.sdkVersion||"",userAgent:typeof navigator<"u"?navigator.userAgent:"unknown"}),t.onAvailablePaymentMethodsLoad?.(a.map(n=>({type:n.config.type,managerType:n.config.type===de.PAYMENT_CARD?Dr.CARD:n.config.implementationType==="NATIVE_SDK"?Dr.NATIVE:Dr.REDIRECT}))),{start:()=>Promise.resolve(),createPaymentMethodManager:async(n,o)=>{let s=a.find(({config:l})=>l.type===n);return s?s instanceof wa?tc(t,e,s,o):s instanceof Da||s instanceof xa||s instanceof Ba?ic(t,e,s):s instanceof _a?oc(t,e,s):nc(t,e,s):(R.warn(`Payment method ${n} not found`),null)},getSDKUtilities:()=>({getCardNetworkAsset:bn,getUIOrderAmount:()=>{let{merchantAmount:n,totalOrderAmount:o,currencyCode:s}=e.configuration.clientSession.order;return Gn(e.locale,n??o,s)},getCDNAssets:async n=>{let o=a.find(({config:c})=>c.type===n);if(!o)return;let{backgroundColor:s,iconUrl:l}=o.config.displayMetadata?.button||{};return{assets:{icon:l?.colored||""},colors:{background:s?.colored||"",main:s?.colored||""},description:o.config.name||null,is_primer_app:!1,name:o.config.name,website:null,goatCdnUrl:""}},getPaymentMethodConfiguration:n=>a.find(({config:o})=>o.type===n)?.config,setBillingAddress:async n=>{let{error:o,data:s}=await e.clientSessionApi.setBillingAddress(n);if(o||!s)throw o||new V({message:"Failed to set billing address"})}}),getAnalyticsUtils:()=>i,createVaultManager(){return Ec(t,e,a)},getAssetsManager:()=>({getCardNetworkAsset:bn,getPaymentMethodAsset:async n=>{let o=a.find(({config:m})=>m.type===n);if(!o)return null;let{backgroundColor:s,iconUrl:l,text:c}=o.config.displayMetadata?.button||{};return{backgroundColor:s,iconUrl:l,paymentMethodName:c,buttonText:c,displayName:o.config.name}}}),refreshClientSession:e.refreshClientConfiguration,getConfiguration:()=>e.configuration,teardown:()=>e.teardown()}}var bn=r=>{let{asset:t,display:e}=ri(r);return{cardUrl:`${Ed}/brand/card/${t}.svg`,displayName:e}},Tc=new Set(["paymentMethodType","last4Digits","network","accountNumberLastFourDigits","bankName"]);function Ut(r){let{id:t,orderId:e,paymentMethodData:a}=r,i={id:t,orderId:e};if(!a||typeof a!="object")return i;let n={};for(let[o,s]of Object.entries(a))Tc.has(o)&&(n[o]=s);return i.paymentMethodData=n,i}var Pc=new Set(["last4Digits","network","accountNumberLastFourDigits","bankName","accountType","email"]);function $n(r){let{id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i,paymentInstrumentData:n,userDescription:o}=r,s={id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i};if(o&&(s.userDescription=o),!n||typeof n!="object")return s;let l={};for(let[c,m]of Object.entries(n))Pc.has(c)&&(l[c]=m);return Object.keys(l).length>0&&(s.paymentInstrumentData=l),s}var Ft=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})}handleExternalCardSubmit(t){this.dispatchCardSubmit(t.source)}dispatchPaymentStart(){this.dispatchEvent("primer:payment-start",void 0)}dispatchPaymentSuccess(t,e){let a=Ut(t),i=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-success",{paymentSummary:a,paymentMethodType:e,timestamp:i})}dispatchPaymentFailure(t,e,a){let i=Math.floor(Date.now()/1e3),n=a?Ut(a):void 0;this.dispatchEvent("primer:payment-failure",{error:t,paymentSummary:n,paymentMethodType:e,timestamp:i})}dispatchVaultMethodsUpdate(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault:methods-update",{vaultedPayments:t,timestamp:e})}dispatchVaultSelectionChange(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault:selection-change",{paymentMethodId:t,timestamp:e})}dispatchVaultSubmit(t){this.dispatchEvent("primer:vault-submit",{source:t})}handleExternalVaultSubmit(t){this.dispatchVaultSubmit(t.source)}dispatchShowOtherPaymentsToggle(t,e){this.dispatchEvent("primer:show-other-payments-toggle",{action:t,source:e})}handleExternalShowOtherPaymentsToggle(t){this.dispatchShowOtherPaymentsToggle(t.action,t.source)}dispatchShowOtherPaymentsToggled(t){this.dispatchEvent("primer:show-other-payments-toggled",{expanded:t})}};var pt=class extends Event{constructor(t,e,a,i){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=a,this.subscribe=i??!1}};var Ht=class{constructor(t,e,a,i){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(n,o)=>{this.unsubscribe&&(this.unsubscribe!==o&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=n,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(n,o)),this.unsubscribe=o},this.host=t,e.context!==void 0){let n=e;this.context=n.context,this.callback=n.callback,this.subscribe=n.subscribe??!1}else this.context=e,this.callback=a,this.subscribe=i??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new pt(this.context,this.host,this.t,this.subscribe))}};var Ka=class{get value(){return this.o}set value(t){this.setValue(t)}setValue(t,e=!1){let a=e||!Object.is(t,this.o);this.o=t,a&&this.updateObservers()}constructor(t){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:a}]of this.subscriptions)e(this.o,a)},t!==void 0&&(this.value=t)}addCallback(t,e,a){if(!a)return void t(this.value);this.subscriptions.has(t)||this.subscriptions.set(t,{disposer:()=>{this.subscriptions.delete(t)},consumerHost:e});let{disposer:i}=this.subscriptions.get(t);t(this.value,i)}clearCallbacks(){this.subscriptions.clear()}};var di=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},$=class extends Ka{constructor(t,e,a){super(e.context!==void 0?e.initialValue:a),this.onContextRequest=i=>{if(i.context!==this.context)return;let n=i.contextTarget??i.composedPath()[0];n!==this.host&&(i.stopPropagation(),this.addCallback(i.callback,n,i.subscribe))},this.onProviderRequest=i=>{if(i.context!==this.context||(i.contextTarget??i.composedPath()[0])===this.host)return;let n=new Set;for(let[o,{consumerHost:s}]of this.subscriptions)n.has(o)||(n.add(o),s.dispatchEvent(new pt(this.context,s,o,!0)));i.stopPropagation()},this.host=t,e.context!==void 0?this.context=e.context:this.context=e,this.attachListeners(),this.host.addController?.(this)}attachListeners(){this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onProviderRequest)}hostConnected(){this.host.dispatchEvent(new di(this.context,this.host))}};function M({context:r,subscribe:t}){return(e,a)=>{typeof a=="object"?a.addInitializer((function(){new Ht(this,{context:r,callback:i=>{e.set.call(this,i)},subscribe:t})})):e.constructor.addInitializer((i=>{new Ht(i,{context:r,callback:n=>{i[a]=n},subscribe:t})}))}}var mt=Symbol("analytics-context");var Ge=Symbol("events-context");var Va="cardNetworksContext";var he="clientOptionsContext";var Yt="computedStylesContext";var Y="headlessInstanceContext";var Ua="configuration";var Fa="klarnaCategoriesContext";var z="managerContext";var ht="paymentMethodsContext";var j="sdkStateContext";var ge="vaultManagerContext";var Ke="vaultManagerCvvContext";function kc(r,t,e,a){let i=r,n=e;return{dispatch:o=>{let s=i,l=t(i,o,n);zn(s,l)?i=l:(i=l,a(l))},getState:()=>Object.freeze({...i}),setCallbacks:o=>{n={...n,...o}}}}function zn(r,t){if(r===t)return!0;if(r==null||t==null||typeof r!="object"||typeof t!="object")return!1;let e=Object.keys(r),a=Object.keys(t);if(e.length!==a.length)return!1;for(let i of e){if(!a.includes(i))return!1;let n=r[i],o=t[i];if(typeof n=="object"&&typeof o=="object"){if(!zn(n,o))return!1}else if(n!==o)return!1}return!0}function ci(r){return(t,e,a)=>{let i=r[e.type];if(!i)throw new Error(`No handler for action type: ${e.type}`);return i(t,e,a)}}var Et=class{constructor(t,e,a,i,n=()=>{this.host.requestUpdate()}){this.host=t;this.stateHandler=n;this.host.addController(this),this._dispatcher=kc(e,a,i,o=>{this.stateHandler(o)})}get currentState(){return this._dispatcher.getState()}dispatch(t){this._dispatcher.dispatch(t)}setCallbacks(t){this._dispatcher.setCallbacks(t)}hostConnected(){}hostDisconnected(){}},Ha=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 jn={isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null},Wn=jn;function Nc(r,t){switch(t.type){case"SET_LOADING":return{...r,isLoading:t.payload};case"SET_PROCESSING":return{...r,isProcessing:t.payload,...t.payload&&{primerJsError:null,paymentFailure:null}};case"SET_SUCCESS":return{...r,isSuccessful:t.payload};case"SET_PRIMER_JS_ERROR":return{...r,primerJsError:t.payload};case"SET_PAYMENT_FAILURE":return{...r,isProcessing:!1,paymentFailure:t.payload};case"COMPLETE_PROCESSING":return{...r,isProcessing:!1,isSuccessful:!0};case"RESET":return{isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null};default:return r}}var Ya=class extends Et{constructor(t){super(t,jn,Nc,null,e=>{t.sdkContextController.setSdkState(e),t.primerEventsController.dispatchSdkState(e)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setProcessing(t){this.dispatch({type:"SET_PROCESSING",payload:t})}setSuccess(t){this.dispatch({type:"SET_SUCCESS",payload:t})}setPrimerJsError(t){this.dispatch({type:"SET_PRIMER_JS_ERROR",payload:t})}setPaymentFailure(t){this.dispatch({type:"SET_PAYMENT_FAILURE",payload:t})}completeProcessing(){this.dispatch({type:"COMPLETE_PROCESSING"})}reset(){this.dispatch({type:"RESET"})}startLoading(){this.setLoading(!0)}completeLoading(){this.setLoading(!1)}startProcessing(){this.setProcessing(!0)}stopProcessing(){this.setProcessing(!1)}resetError(){this.setPrimerJsError(null),this.setPaymentFailure(null)}forceCompleteLoading(){this.setLoading(!1)}};var $a=class{constructor(t){this.sdkStateProvider=null;this.paymentMethodsProvider=null;this.paymentManagerProvider=null;this.cardNetworksContext=null;this.vaultManagerCvvProvider=null;this.clientOptionsContext=null;this.headlessUtilsProvider=null;this.configurationProvider=null;this.klarnaCategoriesProvider=null;this.computedStylesProvider=null;this.analyticsProvider=null;this.eventsProvider=null;(this.host=t).addController(this),this.sdkStateProvider=new $(t,{context:j,initialValue:Wn}),this.paymentMethodsProvider=new $(t,{context:ht,initialValue:null}),this.paymentManagerProvider=new $(t,{context:z,initialValue:new Map}),this.cardNetworksContext=new $(t,{context:Va,initialValue:null}),this.vaultManagerProvider=new $(t,{context:ge,initialValue:null}),this.vaultManagerCvvProvider=new $(t,{context:Ke,initialValue:null}),this.clientOptionsContext=new $(t,{context:he,initialValue:null}),this.klarnaCategoriesProvider=new $(t,{context:Fa,initialValue:{categories:[],isLoading:!0}}),this.headlessUtilsProvider=new $(t,{context:Y,initialValue:null}),this.configurationProvider=new $(t,{context:Ua,initialValue:null}),this.computedStylesProvider=new $(t,{context:Yt,initialValue:null}),this.analyticsProvider=new $(t,{context:mt,initialValue:null}),this.eventsProvider=new $(t,{context:Ge,initialValue:null})}hostConnected(){}setSdkState(t){this.sdkStateProvider?.setValue(t)}setPaymentMethods(t){this.paymentMethodsProvider?.setValue(t)}setPaymentManagers(t){this.paymentManagerProvider?.setValue(t)}setCardNetworks(t){this.cardNetworksContext?.setValue(t)}setVaultManager(t){this.vaultManagerProvider?.setValue(t)}setKlarnaCategories(t){this.klarnaCategoriesProvider?.setValue(t)}setClientOptions(t){this.clientOptionsContext?.setValue(t)}setHeadlessUtils(t){this.headlessUtilsProvider?.setValue(t)}setConfiguration(t){this.configurationProvider?.setValue(t)}setAnalyticsUtils(t){this.analyticsProvider?.setValue(t)}getAnalyticsUtils(){return this.analyticsProvider?.value}setComputedStyles(t){this.computedStylesProvider?.setValue(t)}setVaultManagerCvv(t){this.vaultManagerCvvProvider?.setValue(t)}setEventsController(t){this.eventsProvider?.setValue(t)}};var ui=class{constructor(){x(this,"context",null)}initialize(t){this.context=t,E.debug("Session context initialized:",{checkoutSessionId:t.checkoutSessionId,clientSessionId:t.clientSessionId,primerAccountId:t.primerAccountId,environment:t.environment})}getContext(){return this.context}clear(){E.debug("Session context cleared"),this.context=null}isInitialized(){return this.context!==null}},$t=new ui;var Ic={LOCAL:"https://analytics.dev.data.primer.io/v1/sdk-logs",DEV:"https://analytics.dev.data.primer.io/v1/sdk-logs",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-logs",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-logs",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-logs"};function Jn(r,t){let e=$t.getContext(),i={message:r instanceof Error?r.message:typeof r=="string"?r:JSON.stringify(r)};r instanceof Error&&r.stack&&(i.stack=r.stack),e?(i.checkoutSessionId=e.checkoutSessionId,i.clientSessionId=e.clientSessionId,i.primerAccountId=e.primerAccountId,i.userAgent=e.userAgent):(t?.checkoutSessionId&&(i.checkoutSessionId=t.checkoutSessionId),t?.clientSessionId&&(i.clientSessionId=t.clientSessionId),t?.primerAccountId&&(i.primerAccountId=t.primerAccountId),t?.userAgent&&(i.userAgent=t.userAgent)),t?.metadata&&Object.assign(i,t.metadata),t.status&&Object.assign(i,{status:t.status});let n={message:JSON.stringify(i),hostname:typeof window<"u"?window.location.hostname:"unknown",service:"web-sdk",ddsource:"lambda",ddtags:`env:${e?.environment||t?.environment},version:${e?.sdkVersion||t?.sdkVersion}`};Lc(n,{environment:e?.environment||t?.environment,clientSessionToken:e?.clientSessionToken||t?.clientSessionToken})}function Lc(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){E.debug("\u{1F436}\u{1F436}\u{1F436} [Datadog Log] \u{1F436}\u{1F436}\u{1F436}",r);return}let a=Ic[t||"LOCAL"];if(!a){E.warn("No logging endpoint configured for current environment");return}fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{E.error("Failed to send log event:",i)})}var K=class K{static log(t,...e){K.enabled}static info(t,...e){K.enabled}static warn(t,...e){K.enabled}static error(t,...e){K.enabled&&e.forEach(a=>{a instanceof Error&&a.toJSON})}static errorWithDatadog(t,e){let{error:a,status:i="error"}=e||{};if(K.enabled){a instanceof Error&&a.toJSON;try{let n=a||t,o={status:i,metadata:{sdkOptions:K.sdkOptions,clientToken:K.clientToken}};Jn(n,o)}catch{K.enabled}}}static debug(t,...e){K.enabled}static table(t,e){K.enabled}static time(t){K.enabled}static timeEnd(t){K.enabled}static setSdkOptions(t){K.sdkOptions=t}static setClientToken(t){K.clientToken=t}};x(K,"enabled",!0),x(K,"sdkOptions"),x(K,"clientToken"),x(K,"defaultFont","font-family: Consolas, monospace; font-size: 12px;"),x(K,"brandTag","[PRIMER]"),x(K,"brandStyle",`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${K.defaultFont}`),x(K,"styles",{log:`color: #4CAF50; ${K.defaultFont}`,info:`color: #2196F3; ${K.defaultFont}`,warn:`color: #FF9800; ${K.defaultFont}`,error:`color: #F44336; ${K.defaultFont}`,debug:`color: #9C27B0; ${K.defaultFont}`});var E=K;var Tt=class Tt{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){E.error("Error parsing customStyles property.",e instanceof Error?e:new Error(String(e)))}}isValidCssProperty(t){return/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)}isValidCssValue(t){let a=/^[\w\s#.,%()\-+/!]+$/.test(t);return a||E.warn(`Rejected potentially unsafe CSS value: ${t}`),a}getCssVarName(t){let e=Tt.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(a,i)=>`-${i.toLowerCase()}`)}`,Tt.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let a of Object.keys(t)){let i=t[a];if(!i)continue;if(!this.isValidCssProperty(a)){E.warn(`Skipping invalid CSS property name: ${a}`);continue}if(!this.isValidCssValue(i))continue;let n=this.getCssVarName(a);e.push([n,i])}if(e.length>0)for(let[a,i]of e)this.host.style.setProperty(a,i)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of Tt.cssVarCache.keys()){let e=Tt.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};Tt.cssVarCache=new Map;var za=Tt;var ja=globalThis,Ja=ja.ShadowRoot&&(ja.ShadyCSS===void 0||ja.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,qn=Symbol(),Zn=new WeakMap,Wa=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==qn)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(Ja&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=Zn.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&Zn.set(e,t))}return t}toString(){return this.cssText}},Qn=r=>new Wa(typeof r=="string"?r:r+"",void 0,qn);var pi=(r,t)=>{if(Ja)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=ja.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},Za=Ja?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return Qn(e)})(r):r;var{is:Rc,defineProperty:xc,getOwnPropertyDescriptor:_c,getOwnPropertyNames:wc,getOwnPropertySymbols:Bc,getPrototypeOf:Dc}=Object,gt=globalThis,Xn=gt.trustedTypes,Oc=Xn?Xn.emptyScript:"",Gc=gt.reactiveElementPolyfillSupport,ra=(r,t)=>r,mi={toAttribute(r,t){switch(t){case Boolean:r=r?Oc:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},qa=(r,t)=>!Rc(r,t),eo={attribute:!0,type:String,converter:mi,reflect:!1,hasChanged:qa};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),gt.litPropertyMetadata??(gt.litPropertyMetadata=new WeakMap);var Pt=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=eo){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let a=Symbol(),i=this.getPropertyDescriptor(t,a,e);i!==void 0&&xc(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=_c(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get(){return i?.call(this)},set(o){let s=i?.call(this);n.call(this,o),this.requestUpdate(t,s,a)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??eo}static _$Ei(){if(this.hasOwnProperty(ra("elementProperties")))return;let t=Dc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(ra("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ra("properties"))){let e=this.properties,a=[...wc(e),...Bc(e)];for(let i of a)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[a,i]of e)this.elementProperties.set(a,i)}this._$Eh=new Map;for(let[e,a]of this.elementProperties){let i=this._$Eu(e,a);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let a=new Set(t.flat(1/0).reverse());for(let i of a)e.unshift(Za(i))}else t!==void 0&&e.push(Za(t));return e}static _$Eu(t,e){let a=e.attribute;return a===!1?void 0:typeof a=="string"?a:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let a of e.keys())this.hasOwnProperty(a)&&(t.set(a,this[a]),delete this[a]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return pi(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,a){this._$AK(t,a)}_$EC(t,e){let a=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,a);if(i!==void 0&&a.reflect===!0){let n=(a.converter?.toAttribute!==void 0?a.converter:mi).toAttribute(e,a.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let a=this.constructor,i=a._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=a.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:mi;this._$Em=i,this[i]=o.fromAttribute(e,n.type),this._$Em=null}}requestUpdate(t,e,a){if(t!==void 0){if(a??(a=this.constructor.getPropertyOptions(t)),!(a.hasChanged??qa)(this[t],e))return;this.P(t,e,a)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,e,a){this._$AL.has(t)||this._$AL.set(t,e),a.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let a=this.constructor.elementProperties;if(a.size>0)for(let[i,n]of a)n.wrapped!==!0||this._$AL.has(i)||this[i]===void 0||this.P(i,this[i],n)}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((a=>a.hostUpdate?.())),this.update(e)):this._$EU()}catch(a){throw t=!1,this._$EU(),a}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach((e=>this._$EC(e,this[e])))),this._$EU()}updated(t){}firstUpdated(t){}};Pt.elementStyles=[],Pt.shadowRootOptions={mode:"open"},Pt[ra("elementProperties")]=new Map,Pt[ra("finalized")]=new Map,Gc?.({ReactiveElement:Pt}),(gt.reactiveElementVersions??(gt.reactiveElementVersions=[])).push("2.0.4");var yt={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},_=Symbol(),D=class{get taskComplete(){return this.t||(this.i===1?this.t=new Promise(((t,e)=>{this.o=t,this.h=e})):this.i===3?this.t=Promise.reject(this.l):this.t=Promise.resolve(this.u)),this.t}constructor(t,e,a){this.p=0,this.i=0,(this._=t).addController(this);let i=typeof e=="object"?e:{task:e,args:a};this.v=i.task,this.j=i.args,this.m=i.argsEqual??to,this.k=i.onComplete,this.A=i.onError,this.autoRun=i.autoRun??!0,"initialValue"in i&&(this.u=i.initialValue,this.i=2,this.O=this.T?.())}hostUpdate(){this.autoRun===!0&&this.S()}hostUpdated(){this.autoRun==="afterUpdate"&&this.S()}T(){if(this.j===void 0)return;let t=this.j();if(!Array.isArray(t))throw Error("The args function must return an array");return t}async S(){let t=this.T(),e=this.O;this.O=t,t===e||t===void 0||e!==void 0&&this.m(e,t)||await this.run(t)}async run(t){let e,a;t??(t=this.T()),this.O=t,this.i===1?this.q?.abort():(this.t=void 0,this.o=void 0,this.h=void 0),this.i=1,this.autoRun==="afterUpdate"?queueMicrotask((()=>this._.requestUpdate())):this._.requestUpdate();let i=++this.p;this.q=new AbortController;let n=!1;try{e=await this.v(t,{signal:this.q.signal})}catch(o){n=!0,a=o}if(this.p===i){if(e===_)this.i=0;else{if(n===!1){try{this.k?.(e)}catch{}this.i=2,this.o?.(e)}else{try{this.A?.(a)}catch{}this.i=3,this.h?.(a)}this.u=e,this.l=a}this._.requestUpdate()}}abort(t){this.i===1&&this.q?.abort(t)}get value(){return this.u}get error(){return this.l}get status(){return this.i}render(t){switch(this.i){case 0:return t.initial?.();case 1:return t.pending?.();case 2:return t.complete?.(this.value);case 3:return t.error?.(this.error);default:throw Error("Unexpected status: "+this.i)}}},to=(r,t)=>r===t||r.length===t.length&&r.every(((e,a)=>!qa(e,t[a])));var Qa=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}},Xa=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 Kc={SET_LOADING:(r,t)=>({...r,isLoading:t.payload}),SET_UPDATING:(r,t)=>({...r,isUpdating:t.payload}),INITIALIZE_VAULT_MANAGER:(r,t,e)=>({...r,enabled:t.vaultEnabled,cvvRecapture:t.cvvRecapture,showEmptyState:t.showEmptyState,deleteVaultedPaymentMethod:e.deleteVaultedPaymentMethod,startVaultedPaymentFlow:e.startVaultedPaymentFlow,createCvvInput:e.createCvvInput}),UPDATE_PAYMENT_METHODS:(r,t)=>({...r,vaultedPaymentMethods:t.payload,isLoading:!1,isUpdating:!1}),SET_ERROR:r=>({...r,isLoading:!1,isUpdating:!1}),DISABLE:r=>({...r,enabled:!1}),RESET:()=>ao},Vc={INITIALIZE_CVV:(r,t,e)=>({...r,setCvvInput:e.setCvvInput,setSelectedVaultedPaymentMethod:e.setSelectedVaultedPaymentMethod}),SET_FORM_DIRTY:(r,t)=>({...r,formIsDirty:t.payload}),SET_CVV_INPUT:(r,t)=>({...r,cvvInput:t.payload}),SET_SELECTED_VAULTED_PAYMENT_METHOD:(r,t)=>({...r,selectedVaultedPaymentMethod:t.payload}),RESET_CVV:()=>ro},Uc=ci(Kc),Fc=ci(Vc),ao={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!0,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},ro={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},hi=class extends Et{constructor(t,e){super(t,ao,Uc,e,a=>{t.sdkContextController.setVaultManager(a)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setUpdating(t){this.dispatch({type:"SET_UPDATING",payload:t})}initializeVaultManager(t,e,a,i){this.dispatch({type:"INITIALIZE_VAULT_MANAGER",payload:t,vaultEnabled:e,cvvRecapture:a,showEmptyState:i})}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"})}},gi=class extends Et{constructor(t,e){super(t,ro,Fc,e,a=>{t.sdkContextController.setVaultManagerCvv(a)})}initializeCvv(t){this.dispatch({type:"INITIALIZE_CVV",createCvvInput:t})}setFormDirty(t){this.dispatch({type:"SET_FORM_DIRTY",payload:t})}setCvvInputState(t){this.dispatch({type:"SET_CVV_INPUT",payload:t})}setSelectedPaymentMethod(t){this.dispatch({type:"SET_SELECTED_VAULTED_PAYMENT_METHOD",payload:t})}resetCvv(){this.dispatch({type:"RESET_CVV"})}},ia=class extends Ha{constructor(e){super(e);this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(e)};this.deleteVaultedPaymentMethod=async e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.coreController.updatePaymentMethods(this.vaultManagerState.vaultedPaymentMethods),await this._vaultManager.deleteVaultedPaymentMethod(e),await this.fetchVaultedPaymentMethods()}catch(a){let i=a instanceof Error?a:new Error("Failed to delete payment method");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}};this.setCvvInput=e=>{this.itemController.setCvvInputState(e)};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let e=this.vaultItemState.selectedVaultedPaymentMethod,a=this.vaultManagerState.cvvRecapture,i=this.vaultItemState.cvvInput;if(!e||a&&(!i||i.metadata.error)){this.itemController.setFormDirty(!0);return}this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e.id,a?{cvv:i.valueToken}:void 0)}catch(n){E.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:n});let o=n instanceof Error?n:new Error("Failed to start vaulted payment flow");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o),this.host.sdkStateController.stopProcessing()}};this.setSelectedVaultedPaymentMethod=e=>{this.itemController.setSelectedPaymentMethod(e),this.itemController.setFormDirty(!1),this.host.primerEventsController.dispatchVaultSelectionChange(e?.id??null)};this.coreController=new hi(e,{deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.itemController=new gi(e,{setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)}),this.addController(this.coreController),this.addController(this.itemController),new D(this.host,{task:async([a,i])=>{if(!a||!i?.vaultEnabled)return this.coreController.disable(),_;this.coreController.setLoading(!0);try{let n=a();this._vaultManager=n,this.coreController.initializeVaultManager(n,i.vaultEnabled,!!i.captureVaultedCardCvv,i.showEmptyState??!0),this.itemController.initializeCvv(n.createCvvInput),await this.fetchVaultedPaymentMethods(!0),E.log("VaultManagerController: Vault initialized successfully",{coreState:this.coreController.currentState,cvvState:this.itemController.currentState})}catch(n){E.errorWithDatadog("VaultManagerController: Failed to initialize vault",{error:n});let o=n instanceof Error?n:new Error("Unknown error");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o)}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}initializeVaultManager(e,a){this.createVaultManagerFn=e,this.options=a??null}get vaultManager(){return this._vaultManager}set vaultManager(e){this._vaultManager=e,this.host.requestUpdate()}get options(){return this._options}set options(e){this._options=e,this.host.requestUpdate()}get vaultManagerState(){return this.coreController.currentState}get vaultItemState(){return this.itemController.currentState}hostDisconnected(){super.hostDisconnected(),this.vaultManager=null,this.coreController.reset()}createVaultedPaymentsWrapper(e){let a=new Map;for(let i of e){let n=$n(i);a.set(n.id,n)}return new Xa(a)}updatePaymentMethodsWithEvents(e){this.coreController.updatePaymentMethods(e);let a=this.createVaultedPaymentsWrapper(e);this.host.primerEventsController.dispatchVaultMethodsUpdate(a),this.host.primerJS?.handleVaultedMethodsUpdate(a),E.log("VaultManagerController: Dispatched vault methods update",{methodCount:e.length,filteredMethodCount:a.size()})}async fetchVaultedPaymentMethods(e){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{e||this.coreController.setUpdating(!0);let a=await this._vaultManager.fetchVaultedPaymentMethods();return E.log("VaultManagerController: Fetched payment methods",a),this.updatePaymentMethodsWithEvents(a),a}catch(a){let i=a instanceof Error?a:new Error("Failed to fetch payment methods");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}}};var io=()=>no.randomUUID?.()||Hc(),Hc=()=>("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,r=>(r^Yc()>>r/4).toString(16)),Yc=()=>(no.getRandomValues?.(new Uint8Array(1))[0]??Math.random()*16)&15,no=typeof crypto<"u"?crypto:{};var $c={LOCAL:"",DEV:"https://analytics.dev.data.primer.io/v1/sdk-analytic-events",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-analytic-events",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-analytic-events"},yi=class{sendEvent(t){let e=$t.getContext();if(!e){E.error("Session context not initialized. Call initializeAnalytics() first.");return}let a={id:io(),timestamp:Math.floor(Date.now()/1e3),sdkType:"WEB",eventName:t.eventName,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.clientSessionId,primerAccountId:e.primerAccountId,sdkVersion:e.sdkVersion,userAgent:e.userAgent,eventType:t.eventType,userLocale:t.userLocale,paymentMethod:t.paymentMethod,paymentId:t.paymentId,redirectDestinationUrl:t.redirectDestinationUrl,threedsProvider:t.threedsProvider,threedsResponse:t.threedsResponse};jc(a,e)}},zc=new yi;function oo(r){let t={...r,userAgent:r.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};$t.initialize(t)}function Q(r){zc.sendEvent(r)}function so(){$t.clear()}async function jc(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){E.debug(`Analytics event ${r.eventName}:`,r);return}let a=$c[t];return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{E.error("Failed to send analytics event:",i)})}var na="lit-localize-status";var lo=r=>typeof r!="string"&&"strTag"in r,er=(r,t,e)=>{let a=r[0];for(let i=1;i<r.length;i++)a+=t[e?e[i-1]:i-1],a+=r[i];return a};var oa=(r=>lo(r)?er(r.strings,r.values):r);var b=oa,co=!1;function fi(r){if(co)throw new Error("lit-localize can only be configured once");b=r,co=!0}var vi=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(na,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(na,this.__litLocalizeEventHandler)}},Wc=r=>r.addController(new vi(r)),uo=Wc;var B=()=>(r,t)=>(r.addInitializer(uo),r);var sa=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 Xe=[];for(let r=0;r<256;r++)Xe[r]=(r>>4&15).toString(16)+(r&15).toString(16);function po(r){let t=0,e=8997,a=0,i=33826,n=0,o=40164,s=0,l=52210;for(let c=0;c<r.length;c++)e^=r.charCodeAt(c),t=e*435,a=i*435,n=o*435,s=l*435,n+=e<<8,s+=i<<8,a+=t>>>16,e=t&65535,n+=a>>>16,i=a&65535,l=s+(n>>>16)&65535,o=n&65535;return Xe[l>>8]+Xe[l&255]+Xe[o>>8]+Xe[o&255]+Xe[i>>8]+Xe[i&255]+Xe[e>>8]+Xe[e&255]}var Jc="",Zc="h",qc="s";function mo(r,t){return(t?Zc:qc)+po(typeof r=="string"?r:r.join(Jc))}var ho=new WeakMap,go=new Map;function yo(r,t,e){if(r){let a=e?.id??Qc(t),i=r[a];if(i){if(typeof i=="string")return i;if("strTag"in i)return er(i.strings,t.values,i.values);{let n=ho.get(i);return n===void 0&&(n=i.values,ho.set(i,n)),{...i,values:n.map(o=>t.values[o])}}}}return oa(t)}function Qc(r){let t=typeof r=="string"?r:r.strings,e=go.get(t);return e===void 0&&(e=mo(t,typeof r!="string"&&!("strTag"in r)),go.set(t,e)),e}function Si(r){window.dispatchEvent(new CustomEvent(na,{detail:r}))}var ar="",bi,fo,rr,Ci,vo,kt=new sa;kt.resolve();var tr=0,So=r=>(fi(((t,e)=>yo(vo,t,e))),ar=fo=r.sourceLocale,rr=new Set(r.targetLocales),rr.add(r.sourceLocale),Ci=r.loadLocale,{getLocale:Xc,setLocale:eu}),Xc=()=>ar,eu=r=>{if(r===(bi??ar))return kt.promise;if(!rr||!Ci)throw new Error("Internal error");if(!rr.has(r))throw new Error("Invalid locale code");tr++;let t=tr;return bi=r,kt.settled&&(kt=new sa),Si({status:"loading",loadingLocale:r}),(r===fo?Promise.resolve({templates:void 0}):Ci(r)).then(a=>{tr===t&&(ar=r,bi=void 0,vo=a.templates,Si({status:"ready",readyLocale:r}),kt.resolve())},a=>{tr===t&&(Si({status:"error",errorLocale:r,errorMessage:a.toString()}),kt.reject(a))}),kt.promise};var Ai="en",Mi=["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"],Ei="You must call `loadLocale` first to set up the localized template.",ir,nr,bo=r=>{let t=So({sourceLocale:Ai,targetLocales:Mi,loadLocale:r});ir=t.getLocale,nr=t.setLocale};var Ti=r=>{bo(r)},Pi=r=>{if(!nr)throw new Error(Ei);return nr(r)},ki=()=>{if(!ir)throw new Error(Ei);return ir()};var la=new Set(Mi);la.add(Ai);var Ni=r=>{if(typeof r!="string")return!1;if(r==="en")return!0;let t=r.replace("_","-");if(la.has(t))return!0;let e=t.split("-")[0];return!!la.has(e)},Ii=r=>{if(r==="en")return"en-GB";let t=r.replace("_","-");if(la.has(t))return t;let e=t.split("-")[0];return la.has(e)?e:"en-GB"};var or=globalThis,sr=or.ShadowRoot&&(or.ShadyCSS===void 0||or.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Li=Symbol(),Co=new WeakMap,da=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==Li)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(sr&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=Co.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&Co.set(e,t))}return t}toString(){return this.cssText}},ye=r=>new da(typeof r=="string"?r:r+"",void 0,Li),f=(r,...t)=>{let e=r.length===1?r[0]:t.reduce(((a,i,n)=>a+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[n+1]),r[0]);return new da(e,r,Li)},Ao=(r,t)=>{if(sr)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=or.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},Ri=sr?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return ye(e)})(r):r;var{is:tu,defineProperty:au,getOwnPropertyDescriptor:ru,getOwnPropertyNames:iu,getOwnPropertySymbols:nu,getPrototypeOf:ou}=Object,ft=globalThis,Mo=ft.trustedTypes,su=Mo?Mo.emptyScript:"",lu=ft.reactiveElementPolyfillSupport,ca=(r,t)=>r,ua={toAttribute(r,t){switch(t){case Boolean:r=r?su:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},lr=(r,t)=>!tu(r,t),Eo={attribute:!0,type:String,converter:ua,reflect:!1,useDefault:!1,hasChanged:lr};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ft.litPropertyMetadata??(ft.litPropertyMetadata=new WeakMap);var et=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=Eo){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let a=Symbol(),i=this.getPropertyDescriptor(t,a,e);i!==void 0&&au(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=ru(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get:i,set(o){let s=i?.call(this);n?.call(this,o),this.requestUpdate(t,s,a)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Eo}static _$Ei(){if(this.hasOwnProperty(ca("elementProperties")))return;let t=ou(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(ca("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ca("properties"))){let e=this.properties,a=[...iu(e),...nu(e)];for(let i of a)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[a,i]of e)this.elementProperties.set(a,i)}this._$Eh=new Map;for(let[e,a]of this.elementProperties){let i=this._$Eu(e,a);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let a=new Set(t.flat(1/0).reverse());for(let i of a)e.unshift(Ri(i))}else t!==void 0&&e.push(Ri(t));return e}static _$Eu(t,e){let a=e.attribute;return a===!1?void 0:typeof a=="string"?a:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let a of e.keys())this.hasOwnProperty(a)&&(t.set(a,this[a]),delete this[a]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Ao(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,a){this._$AK(t,a)}_$ET(t,e){let a=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,a);if(i!==void 0&&a.reflect===!0){let n=(a.converter?.toAttribute!==void 0?a.converter:ua).toAttribute(e,a.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let a=this.constructor,i=a._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=a.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:ua;this._$Em=i,this[i]=o.fromAttribute(e,n.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(t,e,a){if(t!==void 0){let i=this.constructor,n=this[t];if(a??(a=i.getPropertyOptions(t)),!((a.hasChanged??lr)(n,e)||a.useDefault&&a.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,a))))return;this.C(t,e,a)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:a,reflect:i,wrapped:n},o){a&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,o??e??this[t]),n!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||a||(e=void 0),this._$AL.set(t,e)),i===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let a=this.constructor.elementProperties;if(a.size>0)for(let[i,n]of a){let{wrapped:o}=n,s=this[i];o!==!0||this._$AL.has(i)||s===void 0||this.C(i,void 0,n,s)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((a=>a.hostUpdate?.())),this.update(e)):this._$EM()}catch(a){throw t=!1,this._$EM(),a}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(t){}firstUpdated(t){}};et.elementStyles=[],et.shadowRootOptions={mode:"open"},et[ca("elementProperties")]=new Map,et[ca("finalized")]=new Map,lu?.({ReactiveElement:et}),(ft.reactiveElementVersions??(ft.reactiveElementVersions=[])).push("2.1.0");var ma=globalThis,dr=ma.trustedTypes,To=dr?dr.createPolicy("lit-html",{createHTML:r=>r}):void 0,_i="$lit$",tt=`lit$${Math.random().toFixed(9).slice(2)}$`,wi="?"+tt,du=`<${wi}>`,Lt=document,ha=()=>Lt.createComment(""),ga=r=>r===null||typeof r!="object"&&typeof r!="function",Bi=Array.isArray,Ro=r=>Bi(r)||typeof r?.[Symbol.iterator]=="function",xi=`[
152
152
  \f\r]`,pa=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Po=/-->/g,ko=/>/g,Nt=RegExp(`>|${xi}(?:([^\\s"'>=/]+)(${xi}*=${xi}*(?:[^
153
- \f\r"'\`<>=]|("|')|))|$)`,"g"),No=/'/g,Io=/"/g,xo=/^(?:script|style|textarea|title)$/i,Di=r=>(t,...e)=>({_$litType$:r,strings:t,values:e}),p=Di(1),Ve=Di(2),Dg=Di(3),re=Symbol.for("lit-noChange"),g=Symbol.for("lit-nothing"),Lo=new WeakMap,It=Lt.createTreeWalker(Lt,129);function _o(r,t){if(!Bi(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return To!==void 0?To.createHTML(t):t}var wo=(r,t)=>{let e=r.length-1,a=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=pa;for(let s=0;s<e;s++){let l=r[s],c,m,y=-1,h=0;for(;h<l.length&&(o.lastIndex=h,m=o.exec(l),m!==null);)h=o.lastIndex,o===pa?m[1]==="!--"?o=Po:m[1]!==void 0?o=ko:m[2]!==void 0?(xo.test(m[2])&&(i=RegExp("</"+m[2],"g")),o=Nt):m[3]!==void 0&&(o=Nt):o===Nt?m[0]===">"?(o=i??pa,y=-1):m[1]===void 0?y=-2:(y=o.lastIndex-m[2].length,c=m[1],o=m[3]===void 0?Nt:m[3]==='"'?Io:No):o===Io||o===No?o=Nt:o===Po||o===ko?o=pa:(o=Nt,i=void 0);let A=o===Nt&&r[s+1].startsWith("/>")?" ":"";n+=o===pa?l+du:y>=0?(a.push(c),l.slice(0,y)+_i+l.slice(y)+tt+A):l+tt+(y===-2?s:A)}return[_o(r,n+(r[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),a]},ya=class r{constructor({strings:t,_$litType$:e},a){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,m]=wo(t,e);if(this.el=r.createElement(c,a),It.currentNode=this.el.content,e===2||e===3){let y=this.el.content.firstChild;y.replaceWith(...y.childNodes)}for(;(i=It.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let y of i.getAttributeNames())if(y.endsWith(_i)){let h=m[o++],A=i.getAttribute(y).split(tt),C=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:C[2],strings:A,ctor:C[1]==="."?ur:C[1]==="?"?pr:C[1]==="@"?mr:xt}),i.removeAttribute(y)}else y.startsWith(tt)&&(l.push({type:6,index:n}),i.removeAttribute(y));if(xo.test(i.tagName)){let y=i.textContent.split(tt),h=y.length-1;if(h>0){i.textContent=dr?dr.emptyScript:"";for(let A=0;A<h;A++)i.append(y[A],ha()),It.nextNode(),l.push({type:2,index:++n});i.append(y[h],ha())}}}else if(i.nodeType===8)if(i.data===wi)l.push({type:2,index:n});else{let y=-1;for(;(y=i.data.indexOf(tt,y+1))!==-1;)l.push({type:7,index:n}),y+=tt.length-1}n++}}static createElement(t,e){let a=Lt.createElement("template");return a.innerHTML=t,a}};function Rt(r,t,e=r,a){if(t===re)return t;let i=a!==void 0?e._$Co?.[a]:e._$Cl,n=ga(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(r),i._$AT(r,e,a)),a!==void 0?(e._$Co??(e._$Co=[]))[a]=i:e._$Cl=i),i!==void 0&&(t=Rt(r,i._$AS(r,t.values),i,a)),t}var cr=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:a}=this._$AD,i=(t?.creationScope??Lt).importNode(e,!0);It.currentNode=i;let n=It.nextNode(),o=0,s=0,l=a[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new zt(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new hr(n,this,t)),this._$AV.push(c),l=a[++s]}o!==l?.index&&(n=It.nextNode(),o++)}return It.currentNode=Lt,i}p(t){let e=0;for(let a of this._$AV)a!==void 0&&(a.strings!==void 0?(a._$AI(t,a,e),e+=a.strings.length-2):a._$AI(t[e])),e++}},zt=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,a,i){this.type=2,this._$AH=g,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=a,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Rt(this,t,e),ga(t)?t===g||t==null||t===""?(this._$AH!==g&&this._$AR(),this._$AH=g):t!==this._$AH&&t!==re&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ro(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!==g&&ga(this._$AH)?this._$AA.nextSibling.data=t:this.T(Lt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:a}=t,i=typeof a=="number"?this._$AC(t):(a.el===void 0&&(a.el=ya.createElement(_o(a.h,a.h[0]),this.options)),a);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new cr(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=Lo.get(t.strings);return e===void 0&&Lo.set(t.strings,e=new ya(t)),e}k(t){Bi(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,a,i=0;for(let n of t)i===e.length?e.push(a=new r(this.O(ha()),this.O(ha()),this,this.options)):a=e[i],a._$AI(n),i++;i<e.length&&(this._$AR(a&&a._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let a=t.nextSibling;t.remove(),t=a}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},xt=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,a,i,n){this.type=1,this._$AH=g,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,a.length>2||a[0]!==""||a[1]!==""?(this._$AH=Array(a.length-1).fill(new String),this.strings=a):this._$AH=g}_$AI(t,e=this,a,i){let n=this.strings,o=!1;if(n===void 0)t=Rt(this,t,e,0),o=!ga(t)||t!==this._$AH&&t!==re,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Rt(this,s[a+l],e,l),c===re&&(c=this._$AH[l]),o||(o=!ga(c)||c!==this._$AH[l]),c===g?t=g:t!==g&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===g?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},ur=class extends xt{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===g?void 0:t}},pr=class extends xt{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==g)}},mr=class extends xt{constructor(t,e,a,i,n){super(t,e,a,i,n),this.type=5}_$AI(t,e=this){if((t=Rt(this,t,e,0)??g)===re)return;let a=this._$AH,i=t===g&&a!==g||t.capture!==a.capture||t.once!==a.once||t.passive!==a.passive,n=t!==g&&(a===g||i);i&&this.element.removeEventListener(this.name,this,a),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},hr=class{constructor(t,e,a){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=a}get _$AU(){return this._$AM._$AU}_$AI(t){Rt(this,t)}},Bo={M:_i,P:tt,A:wi,C:1,L:wo,R:cr,D:Ro,V:Rt,I:zt,H:xt,N:pr,U:mr,B:ur,F:hr},cu=ma.litHtmlPolyfillSupport;cu?.(ya,zt),(ma.litHtmlVersions??(ma.litHtmlVersions=[])).push("3.3.0");var Do=(r,t,e)=>{let a=e?.renderBefore??t,i=a._$litPart$;if(i===void 0){let n=e?.renderBefore??null;a._$litPart$=i=new zt(t.insertBefore(ha(),n),n,void 0,e??{})}return i._$AI(r),i};var fa=globalThis,v=class extends et{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=Do(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return re}};v._$litElement$=!0,v.finalized=!0,fa.litElementHydrateSupport?.({LitElement:v});var uu=fa.litElementPolyfillSupport;uu?.({LitElement:v});(fa.litElementVersions??(fa.litElementVersions=[])).push("4.2.0");var S=r=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(r,t)})):customElements.define(r,t)};var pu={attribute:!0,type:String,converter:ua,reflect:!1,hasChanged:lr},mu=(r=pu,t,e)=>{let{kind:a,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),a==="setter"&&((r=Object.create(r)).wrapped=!0),n.set(e.name,r),a==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,r)},init(s){return s!==void 0&&this.C(o,void 0,r,s),s}}}if(a==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,r)}}throw Error("Unsupported decorator location: "+a)};function u(r){return(t,e)=>typeof e=="object"?mu(r,t,e):((a,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,a),o?Object.getOwnPropertyDescriptor(i,n):void 0})(r,t,e)}function P(r){return u({...r,state:!0,attribute:!1})}var _t=(r,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(r,t,e),e);function Ue(r,t){return(e,a,i)=>{let n=o=>o.renderRoot?.querySelector(r)??null;if(t){let{get:o,set:s}=typeof a=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return _t(e,a,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return _t(e,a,{get(){return n(this)}})}}function L(r,t,e){return r?t(r):e?.(r)}var k=f` * { box-sizing: border-box; } `,Oo=f` :host { display: block; isolation: isolate; position: relative; width: 100%; //Keep the CSS loader in the same position - check css-loader-inline.ts min-height: 64px; } `;var Go="https://sdk.primer.io/web/v2-latest/Primer.min.js",Ie="20px";var gr=class{constructor(t){this.paymentMethods=null;this.paymentManagers=null;this.headlessInstance=t}setPaymentMethods(t){this.paymentMethods=t}setPaymentManagers(t){this.paymentManagers=t}async refreshSession(){if(!this.headlessInstance){E.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw E.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods.toArray():(E.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleBeforePaymentCreate(t,e){if(this.onPaymentPrepare){let a={continuePaymentCreation:()=>{E.info("PrimerJS: Payment creation continuing"),e.continuePaymentCreation()},abortPaymentCreation:()=>{E.info("PrimerJS: Payment creation aborted"),e.abortPaymentCreation()}};this.onPaymentPrepare(t,a)}else E.info("PrimerJS: No payment prepare handler, continuing by default"),e.continuePaymentCreation()}handleVaultedMethodsUpdate(t){if(this.onVaultedMethodsUpdate){let e=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,timestamp:e})}}setCardholderName(t){if(!this.paymentManagers){E.warn("PrimerJS: Payment managers not available - setCardholderName cannot be called yet");return}let e=this.paymentManagers.get("PAYMENT_CARD");if(!e||e.type!=="PAYMENT_CARD"){E.warn("PrimerJS: Card payment manager not available");return}try{e.manager.setCardholderName(t)}catch(a){E.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:a})}}};var wt={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",AUTOMATED_CLEARING_HOUSE:"AUTOMATED_CLEARING_HOUSE",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_ACH:"STRIPE_ACH",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL_ORDER",PAYPAL_VAULTED:"PAYPAL_BILLING_AGREEMENT",GO_CARDLESS:"GOCARDLESS",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",KLARNA_CUSTOMER_TOKEN:"KLARNA_CUSTOMER_TOKEN",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"},va={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"};var yr=class r extends Error{constructor(t,e){super(e.message),this.name="PrimerClientError",this.code=t,this.diagnosticsId=e.diagnosticsId||null,this.data=e.data,this.isFromDeveloper=e.isFromDeveloper||!1}static fromErrorCode(t,e){return new r(t,e)}};var fr=typeof window<"u"&&typeof window.document<"u";function hu(r){return document.querySelector(`script[src^="${r}"]`)}function gu(r,t){let e=document.createElement("script");return e.setAttribute("src",r),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function Ko(r,t=!1){if(!fr)throw new Error("Cannot load script in server environment");let e=hu(r)??gu(r,t);return new Promise((a,i)=>{e.onload=()=>{a()},e.onerror=()=>{i(new Error(`Failed to load script: ${r}`))},e.parentNode||document.head.appendChild(e)})}var X={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Me=r=>(...t)=>({_$litDirective$:r,values:t}),Fe=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,a){this._$Ct=t,this._$AM=e,this._$Ci=a}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};var Sa=class extends Fe{constructor(t){if(super(t),this.it=g,t.type!==X.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===g||t==null)return this._t=void 0,this.it=t;if(t===re)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;let e=[t];return e.raw=e,this._t={_$litType$:this.constructor.resultType,strings:e,values:[]}}};Sa.directiveName="unsafeHTML",Sa.resultType=1;var Vo=Me(Sa);var Uo=Symbol.for("primer-sdk-core-dialog-access");function Fo(r){return{token:Uo,content:r}}function Oi(r){return r!==void 0&&r.token===Uo&&typeof r.content=="string"}var Ho=f` :host { display: block; } .content-container { width: 100%; height: 100%; display: flex; flex-direction: column; background-color: var(--primer-color-background-outlined-default); } .error { display: flex; align-items: center; justify-content: center; padding: var(--primer-space-large); color: var(--primer-color-text-danger); font-family: var(--primer-typography-body-medium-font); font-size: var(--primer-typography-body-medium-size); } `;var ce=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.open=!1}openDialog(){this.open=!0}closeDialog(){let e=document.querySelector("primer-dialog");if(e){e.startExitAnimation();let a=()=>{this.open=!1,this.removeEventListener("primer-dialog-close",a)};this.addEventListener("primer-dialog-close",a)}else this.open=!1}renderContent(){return p`<div class="content-container"><slot></slot>${this.renderSecureHtmlContent()}</div>`}renderSecureHtmlContent(){return this.secureHtmlContent?Oi(this.secureHtmlContent)?p`${Vo(this.secureHtmlContent.content)}`:(E.warn("PortalDialogComponent: Invalid access token provided for htmlContent. Content will not be rendered."),g):g}renderDialog(){return this.open?p`<primer-portal><primer-dialog .open=${this.open} size=${this.size} .showCloseButton=${!1} @primer-dialog-close="${()=>this.closeDialog()}" >${this.renderContent()}</primer-dialog></primer-portal>`:g}connectedCallback(){super.connectedCallback(),this.open||this.openDialog()}updated(e){if(super.updated(e),e.has("secureHtmlContent")){let a=this.secureHtmlContent;a&&!Oi(a)&&(E.errorWithDatadog("PortalDialogComponent: Invalid access token provided for htmlContent. Content will not be rendered."),this.secureHtmlContent=void 0)}e.has("open")&&this.open&&this.onOpen&&this.onOpen(),e.has("open")&&this.open&&this.onContentRendered&&this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.onContentRendered?.()})})}render(){return p`${this.renderDialog()}`}};ce.styles=[k,Ho],d([u({type:String})],ce.prototype,"size",2),d([u({type:Boolean})],ce.prototype,"showCloseButton",2),d([u({type:Object})],ce.prototype,"onOpen",2),d([u({type:Object})],ce.prototype,"onContentRendered",2),d([u({type:Object,converter:{fromAttribute:()=>{},toAttribute:()=>null}})],ce.prototype,"secureHtmlContent",2),d([P()],ce.prototype,"open",2),ce=d([S("primer-portal-dialog"),B()],ce);var vr=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let a=Fo(t.htmlContent),i=new ce;i.secureHtmlContent=a,i.size="large",i.showCloseButton=!1,i.onContentRendered=t.onContentReady;let n=()=>{this.currentDialog=null,this.currentResolver=null,e({success:!1})};i.addEventListener("primer-dialog-close",n),this.currentDialog=i,this.currentResolver=e,document.body.appendChild(i)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}};var Gi="0.8.1",Sr=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 D(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()}),new D(t,{args:()=>[this.sdkInstanceTask.value,this.paymentsList],task:this.initializeLitContext()})}set paymentsList(t){this._paymentsList=t,this.host.requestUpdate()}get paymentsList(){return this._paymentsList}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkStateController.startLoading(),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.getAnalyticsUtils()){let e=this.host.sdkStateController.currentState;(e.isProcessing||e.isLoading||this.currentSdkInstance)&&Q({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}normalizeOptionsForLegacySdk(t){if(t.sdkCore!==!1)return t.sdkCore=!0,t;let e={...t};if(e.card?.cardholderName){let a={...e.card.cardholderName};a.visible===!1&&(a.required=!1),e.card={...e.card,cardholderName:a}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkStateController.currentState.isLoading&&(E.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkStateController.completeLoading())},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.paymentsList=[],this.createPaymentMethodManager=null,this.host.sdkStateController.reset(),this.currentSdkInstance.teardown?.(),E.info("SDK instance cleaned up")}catch(t){E.errorWithDatadog("Error cleaning up SDK instance",{error:t})}so(),E.setClientToken(void 0),E.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=Go){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){E.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await Ko(t),await e.Primer.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return E.warn("Component disconnected, aborting SDK initialization"),_;if(!t||!e)return _;this.cleanupResources();let a;try{let i;if(e.sdkCore!==!1){let l=new vr;i={createHeadless:(m,y)=>Yn(m,{...y,dialogProvider:l,sdkVersion:Gi})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new gr(null);let n=this.normalizeOptionsForLegacySdk(e);E.setClientToken(t),E.setSdkOptions(n);let o=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:l=>{this.isDisconnected||(E.info("Configuration payment methods:",l),this.paymentsList=l)},onCheckoutComplete:({payment:l})=>{if(this.isDisconnected)return;E.info("Payment completed:",l);let c=l?.paymentMethodData?.paymentMethodType||"UNKNOWN";if(this.host.sdkStateController.completeProcessing(),l&&this.host.primerEventsController.dispatchPaymentSuccess(l,c),Q({eventName:"PAYMENT_SUCCESS",paymentId:l?.id}),this.primerJS?.onPaymentSuccess&&l){let m=Math.floor(Date.now()/1e3);this.primerJS.onPaymentSuccess({payment:Ut(l),paymentMethodType:c,timestamp:m})}},onCheckoutFail:(l,c)=>{if(this.isDisconnected)return;(C=>typeof C=="object"&&C!==null&&"response"in C&&typeof C.response=="object"&&C.response!==null&&"status"in C.response&&typeof C.response.status=="number")(l)&&l.response.status>=500?E.errorWithDatadog("Payment failed with server error",{error:l}):E.error("Payment failed:",l);let h=c.payment?.paymentMethodData?.paymentMethodType||"UNKNOWN",A=l instanceof yr?{code:l.code||"UNKNOWN_ERROR",message:l.message||"Unknown error occurred",diagnosticsId:l.diagnosticsId,data:l.data}:(()=>{let C=l,T=C instanceof Error&&"code"in C&&typeof C.code=="string"?C.code:"UNKNOWN_ERROR",N=C instanceof Error?C.message:"Unknown error occurred";return{code:T,message:N,data:{error:l}}})();if(this.host.sdkStateController.setPaymentFailure(A),this.host.primerEventsController.dispatchPaymentFailure({code:A.code,message:A.message,diagnosticsId:"diagnosticsId"in A?A.diagnosticsId??void 0:void 0,data:A.data},h,c.payment),Q({eventName:"PAYMENT_FAILURE",paymentId:c.payment?.id}),this.primerJS?.onPaymentFailure){let C=Math.floor(Date.now()/1e3);this.primerJS.onPaymentFailure({error:{code:A.code,message:A.message,diagnosticsId:"diagnosticsId"in A?A.diagnosticsId??void 0:void 0,data:A.data},payment:c.payment?Ut(c.payment):void 0,paymentMethodType:h,timestamp:C})}},onBeforePaymentCreate:(l,c)=>{if(this.isDisconnected)return;this.host.sdkStateController.currentState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:l.paymentMethodType}),this.host.sdkStateController.startProcessing(),this.primerJS?this.primerJS.handleBeforePaymentCreate(l,c):c?.continuePaymentCreation()},onPaymentMethodAction:(l,c)=>{this.isDisconnected||l==="PAYMENT_METHOD_UNSELECTED"&&this.host.sdkStateController.stopProcessing()},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.createPaymentMethodManager=o.createPaymentMethodManager.bind(o),this.currentSdkInstance=o,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:o,writable:!1}),await o.start(),this.isDisconnected)return this.cleanupResources(),_;this.host.sdkContextController.setClientOptions(e),this.primerJS&&this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS);let s=o.getSDKUtilities();if(a=o.getAnalyticsUtils?.(),a&&(this.host.sdkContextController.setAnalyticsUtils({...a,sdkVersion:Gi}),oo({environment:a.environment,checkoutSessionId:a.checkoutSessionId,clientSessionId:a.clientSessionId||"",primerAccountId:a.primerAccountId||"",sdkVersion:Gi,clientSessionToken:a.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),Q({eventName:"SDK_INIT_START"})),this.host.sdkContextController.setHeadlessUtils(s),e.sdkCore&&o.getConfiguration){let l=o.getConfiguration();this.host.sdkContextController.setConfiguration(l)}return this.host.vaultManagerController.initializeVaultManager(o.createVaultManager.bind(o),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!s.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState}),o}catch(i){throw i instanceof Error&&(E.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkStateController.setPrimerJsError(i)),this.cleanupResources(),i}}}initializeLitContext(){return async([t,e])=>{if(this.isDisconnected)return _;if(!t||!e.length)return _;let a=new Map,i=new Map;try{for(let o of e){if(this.isDisconnected)break;let s=await this.initializePaymentMethodManager(o)();o&&s&&(a.set(o.type,o),i.set(o.type,s))}if(this.isDisconnected)return _;let n=new Qa(a);return this.host.sdkContextController.setPaymentManagers(i),this.host.sdkContextController.setPaymentMethods(n),this.primerJS&&(this.primerJS.setPaymentMethods(n),this.primerJS.setPaymentManagers(i)),this.host.primerEventsController.dispatchPaymentMethods(n),E.info("Initialized payment methods:",n.toArray()),a}catch(n){if(n instanceof Error)throw this.host.sdkStateController.setPrimerJsError(n),n;return null}finally{this.clearLoadingTimeout(),this.isDisconnected||(this.host.sdkStateController.completeLoading(),Q({eventName:"SDK_INIT_END"}))}}}initializePaymentMethodManager(t){let{type:e,managerType:a}=t;return async()=>{if(this.isDisconnected||!this.createPaymentMethodManager)return null;if(a==="KLARNA"){let i=await this.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:n=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:n,isLoading:!1})}});return i?{type:e,manager:i}:null}try{if(a==="CARD"){let n=await this.createPaymentMethodManager("PAYMENT_CARD",{onCardNetworksChange:o=>{this.isDisconnected||this.host.cardNetworkController.processCardNetworkChangeEvent(o)},onCardNetworksLoading:()=>{this.isDisconnected||this.host.cardNetworkController.setCardNetworksLoading()}});return n?{type:e,manager:n}:null}let i=await this.createPaymentMethodManager(e);return i?{type:e,manager:i}:null}catch(i){return E.errorWithDatadog(`Failed to initialize manager for ${e}`,{error:i}),null}}}};var br=class{constructor(t){this.host=t,t.addController(this)}_error(t){let{error:e}=t.detail;this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:e.message})}_mandateConfirmed(){this.host.sdkStateController.completeProcessing()}_mandateDeclined(){this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:"Mandate declined"})}hostConnected(){this.host.addEventListener("primer-ach-error",this._error.bind(this)),this.host.addEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.addEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}hostDisconnected(){this.host.removeEventListener("primer-ach-error",this._error.bind(this)),this.host.removeEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.removeEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}};var yu=qi({"../../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")});Ti(r=>yu(`../../localization/lit-localize/locales/${r}.ts`));var fu={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},Ee=class extends v{constructor(){super();this.customStyles="";this.clientToken="";this.options={};this.disableLoader=!1;this._jsInitialized=!1;this.previousLoadingState=!0;this.hasAssignedContent=!1;this._loadingTimeoutId=null;this._eventListenerController=null;this.locale="en-GB";this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new $a(this),this.sdkStateController=new Ya(this),this.primerEventsController=new Ft(this),this.styleProcessingController=new za(this),this.vaultManagerController=new ia(this),this.cardNetworkController=new Ma(this),this.achPaymentEventsController=new br(this),this.headlessSdkController=new Sr(this)}set jsInitialized(e){this.requestUpdate(),this._jsInitialized=e}get jsInitialized(){return this._jsInitialized}get primerJS(){return this.headlessSdkController?.primerJSInstance??void 0}connectedCallback(){super.connectedCallback(),this.sdkContextController.setEventsController(this.primerEventsController),this._eventListenerController=new AbortController,document.addEventListener("primer:card-submit",this.handleExternalCardSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:vault-submit",this.handleExternalVaultSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:show-other-payments-toggle",this.handleExternalShowOtherPaymentsToggle.bind(this),{signal:this._eventListenerController.signal})}attributeChangedCallback(e,a,i){e===fu.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,a,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkStateController?.currentState.isLoading&&this.sdkStateController.forceCompleteLoading(),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(Ni(this.options?.locale)?this.locale=Ii(this.options?.locale):E.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to default locale `en-GB`")),Pi(this.locale||"en-GB"))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}handleExternalCardSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:card-submit",e.detail)}handleExternalVaultSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:vault-submit",e.detail)}handleExternalShowOtherPaymentsToggle(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:show-other-payments-toggle",e.detail)}checkLoadingStateChange(){let e=this.sdkStateController?.currentState.isLoading||!1;this.previousLoadingState&&!e&&(this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"})),this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkStateController?.currentState.isLoading&&(E.warn("Loading timeout in component, forcing completion"),this.sdkStateController.forceCompleteLoading(),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkStateController.currentState,a=e.isLoading,i=e.primerJsError,n=!a&&!i;return p` ${L(a,()=>g)} ${L(i,()=>p`<primer-checkout-error></primer-checkout-error>`)} ${L(n,()=>p`<slot name="main" @slotchange=${this.onSlotChange}></slot>${L(this.hasAssignedContent,()=>g,()=>p`<primer-main></primer-main>`)} `,()=>g)} `}addEventListener(e,a,i){super.addEventListener(e,a,i)}removeEventListener(e,a,i){super.removeEventListener(e,a,i)}};Ee.styles=[k,Oo],d([u({type:String,attribute:"custom-styles"})],Ee.prototype,"customStyles",2),d([u({type:String,attribute:"client-token"})],Ee.prototype,"clientToken",2),d([u({type:Object})],Ee.prototype,"options",2),d([u({type:Boolean,attribute:"loader-disabled"})],Ee.prototype,"disableLoader",2),d([u({type:Boolean,reflect:!0,attribute:"js-initialized"})],Ee.prototype,"_jsInitialized",2),d([Ue("slot")],Ee.prototype,"defaultSlot",2),d([P()],Ee.prototype,"previousLoadingState",2),Ee=d([B(),S("primer-checkout")],Ee);function vu(r){return document.querySelector(`#${r}`)}function Su(r,t){let e=document.createElement("style");return e.textContent=r,e.id=t,e}function ba(r,t,e=!0){if(!fr||vu(t))return;let i=Su(r,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var Yo=`
153
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),No=/'/g,Io=/"/g,xo=/^(?:script|style|textarea|title)$/i,Di=r=>(t,...e)=>({_$litType$:r,strings:t,values:e}),p=Di(1),Ve=Di(2),Dg=Di(3),re=Symbol.for("lit-noChange"),g=Symbol.for("lit-nothing"),Lo=new WeakMap,It=Lt.createTreeWalker(Lt,129);function _o(r,t){if(!Bi(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return To!==void 0?To.createHTML(t):t}var wo=(r,t)=>{let e=r.length-1,a=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=pa;for(let s=0;s<e;s++){let l=r[s],c,m,y=-1,h=0;for(;h<l.length&&(o.lastIndex=h,m=o.exec(l),m!==null);)h=o.lastIndex,o===pa?m[1]==="!--"?o=Po:m[1]!==void 0?o=ko:m[2]!==void 0?(xo.test(m[2])&&(i=RegExp("</"+m[2],"g")),o=Nt):m[3]!==void 0&&(o=Nt):o===Nt?m[0]===">"?(o=i??pa,y=-1):m[1]===void 0?y=-2:(y=o.lastIndex-m[2].length,c=m[1],o=m[3]===void 0?Nt:m[3]==='"'?Io:No):o===Io||o===No?o=Nt:o===Po||o===ko?o=pa:(o=Nt,i=void 0);let A=o===Nt&&r[s+1].startsWith("/>")?" ":"";n+=o===pa?l+du:y>=0?(a.push(c),l.slice(0,y)+_i+l.slice(y)+tt+A):l+tt+(y===-2?s:A)}return[_o(r,n+(r[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),a]},ya=class r{constructor({strings:t,_$litType$:e},a){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,m]=wo(t,e);if(this.el=r.createElement(c,a),It.currentNode=this.el.content,e===2||e===3){let y=this.el.content.firstChild;y.replaceWith(...y.childNodes)}for(;(i=It.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let y of i.getAttributeNames())if(y.endsWith(_i)){let h=m[o++],A=i.getAttribute(y).split(tt),C=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:C[2],strings:A,ctor:C[1]==="."?ur:C[1]==="?"?pr:C[1]==="@"?mr:xt}),i.removeAttribute(y)}else y.startsWith(tt)&&(l.push({type:6,index:n}),i.removeAttribute(y));if(xo.test(i.tagName)){let y=i.textContent.split(tt),h=y.length-1;if(h>0){i.textContent=dr?dr.emptyScript:"";for(let A=0;A<h;A++)i.append(y[A],ha()),It.nextNode(),l.push({type:2,index:++n});i.append(y[h],ha())}}}else if(i.nodeType===8)if(i.data===wi)l.push({type:2,index:n});else{let y=-1;for(;(y=i.data.indexOf(tt,y+1))!==-1;)l.push({type:7,index:n}),y+=tt.length-1}n++}}static createElement(t,e){let a=Lt.createElement("template");return a.innerHTML=t,a}};function Rt(r,t,e=r,a){if(t===re)return t;let i=a!==void 0?e._$Co?.[a]:e._$Cl,n=ga(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(r),i._$AT(r,e,a)),a!==void 0?(e._$Co??(e._$Co=[]))[a]=i:e._$Cl=i),i!==void 0&&(t=Rt(r,i._$AS(r,t.values),i,a)),t}var cr=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:a}=this._$AD,i=(t?.creationScope??Lt).importNode(e,!0);It.currentNode=i;let n=It.nextNode(),o=0,s=0,l=a[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new zt(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new hr(n,this,t)),this._$AV.push(c),l=a[++s]}o!==l?.index&&(n=It.nextNode(),o++)}return It.currentNode=Lt,i}p(t){let e=0;for(let a of this._$AV)a!==void 0&&(a.strings!==void 0?(a._$AI(t,a,e),e+=a.strings.length-2):a._$AI(t[e])),e++}},zt=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,a,i){this.type=2,this._$AH=g,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=a,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Rt(this,t,e),ga(t)?t===g||t==null||t===""?(this._$AH!==g&&this._$AR(),this._$AH=g):t!==this._$AH&&t!==re&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ro(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!==g&&ga(this._$AH)?this._$AA.nextSibling.data=t:this.T(Lt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:a}=t,i=typeof a=="number"?this._$AC(t):(a.el===void 0&&(a.el=ya.createElement(_o(a.h,a.h[0]),this.options)),a);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new cr(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=Lo.get(t.strings);return e===void 0&&Lo.set(t.strings,e=new ya(t)),e}k(t){Bi(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,a,i=0;for(let n of t)i===e.length?e.push(a=new r(this.O(ha()),this.O(ha()),this,this.options)):a=e[i],a._$AI(n),i++;i<e.length&&(this._$AR(a&&a._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let a=t.nextSibling;t.remove(),t=a}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},xt=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,a,i,n){this.type=1,this._$AH=g,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,a.length>2||a[0]!==""||a[1]!==""?(this._$AH=Array(a.length-1).fill(new String),this.strings=a):this._$AH=g}_$AI(t,e=this,a,i){let n=this.strings,o=!1;if(n===void 0)t=Rt(this,t,e,0),o=!ga(t)||t!==this._$AH&&t!==re,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Rt(this,s[a+l],e,l),c===re&&(c=this._$AH[l]),o||(o=!ga(c)||c!==this._$AH[l]),c===g?t=g:t!==g&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===g?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},ur=class extends xt{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===g?void 0:t}},pr=class extends xt{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==g)}},mr=class extends xt{constructor(t,e,a,i,n){super(t,e,a,i,n),this.type=5}_$AI(t,e=this){if((t=Rt(this,t,e,0)??g)===re)return;let a=this._$AH,i=t===g&&a!==g||t.capture!==a.capture||t.once!==a.once||t.passive!==a.passive,n=t!==g&&(a===g||i);i&&this.element.removeEventListener(this.name,this,a),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},hr=class{constructor(t,e,a){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=a}get _$AU(){return this._$AM._$AU}_$AI(t){Rt(this,t)}},Bo={M:_i,P:tt,A:wi,C:1,L:wo,R:cr,D:Ro,V:Rt,I:zt,H:xt,N:pr,U:mr,B:ur,F:hr},cu=ma.litHtmlPolyfillSupport;cu?.(ya,zt),(ma.litHtmlVersions??(ma.litHtmlVersions=[])).push("3.3.0");var Do=(r,t,e)=>{let a=e?.renderBefore??t,i=a._$litPart$;if(i===void 0){let n=e?.renderBefore??null;a._$litPart$=i=new zt(t.insertBefore(ha(),n),n,void 0,e??{})}return i._$AI(r),i};var fa=globalThis,v=class extends et{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=Do(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return re}};v._$litElement$=!0,v.finalized=!0,fa.litElementHydrateSupport?.({LitElement:v});var uu=fa.litElementPolyfillSupport;uu?.({LitElement:v});(fa.litElementVersions??(fa.litElementVersions=[])).push("4.2.0");var S=r=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(r,t)})):customElements.define(r,t)};var pu={attribute:!0,type:String,converter:ua,reflect:!1,hasChanged:lr},mu=(r=pu,t,e)=>{let{kind:a,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),a==="setter"&&((r=Object.create(r)).wrapped=!0),n.set(e.name,r),a==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,r)},init(s){return s!==void 0&&this.C(o,void 0,r,s),s}}}if(a==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,r)}}throw Error("Unsupported decorator location: "+a)};function u(r){return(t,e)=>typeof e=="object"?mu(r,t,e):((a,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,a),o?Object.getOwnPropertyDescriptor(i,n):void 0})(r,t,e)}function P(r){return u({...r,state:!0,attribute:!1})}var _t=(r,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(r,t,e),e);function Ue(r,t){return(e,a,i)=>{let n=o=>o.renderRoot?.querySelector(r)??null;if(t){let{get:o,set:s}=typeof a=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return _t(e,a,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return _t(e,a,{get(){return n(this)}})}}function L(r,t,e){return r?t(r):e?.(r)}var k=f` * { box-sizing: border-box; } `,Oo=f` :host { display: block; isolation: isolate; position: relative; width: 100%; //Keep the CSS loader in the same position - check css-loader-inline.ts min-height: 64px; } `;var Go="https://sdk.primer.io/web/v2-latest/Primer.min.js",Ie="20px";var gr=class{constructor(t){this.paymentMethods=null;this.paymentManagers=null;this.headlessInstance=t}setPaymentMethods(t){this.paymentMethods=t}setPaymentManagers(t){this.paymentManagers=t}async refreshSession(){if(!this.headlessInstance){E.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw E.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods.toArray():(E.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleBeforePaymentCreate(t,e){if(this.onPaymentPrepare){let a={continuePaymentCreation:()=>{E.info("PrimerJS: Payment creation continuing"),e.continuePaymentCreation()},abortPaymentCreation:()=>{E.info("PrimerJS: Payment creation aborted"),e.abortPaymentCreation()}};this.onPaymentPrepare(t,a)}else E.info("PrimerJS: No payment prepare handler, continuing by default"),e.continuePaymentCreation()}handleVaultedMethodsUpdate(t){if(this.onVaultedMethodsUpdate){let e=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,timestamp:e})}}setCardholderName(t){if(!this.paymentManagers){E.warn("PrimerJS: Payment managers not available - setCardholderName cannot be called yet");return}let e=this.paymentManagers.get("PAYMENT_CARD");if(!e||e.type!=="PAYMENT_CARD"){E.warn("PrimerJS: Card payment manager not available");return}try{e.manager.setCardholderName(t)}catch(a){E.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:a})}}};var wt={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",AUTOMATED_CLEARING_HOUSE:"AUTOMATED_CLEARING_HOUSE",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_ACH:"STRIPE_ACH",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL_ORDER",PAYPAL_VAULTED:"PAYPAL_BILLING_AGREEMENT",GO_CARDLESS:"GOCARDLESS",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",KLARNA_CUSTOMER_TOKEN:"KLARNA_CUSTOMER_TOKEN",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"},va={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"};var yr=class r extends Error{constructor(t,e){super(e.message),this.name="PrimerClientError",this.code=t,this.diagnosticsId=e.diagnosticsId||null,this.data=e.data,this.isFromDeveloper=e.isFromDeveloper||!1}static fromErrorCode(t,e){return new r(t,e)}};var fr=typeof window<"u"&&typeof window.document<"u";function hu(r){return document.querySelector(`script[src^="${r}"]`)}function gu(r,t){let e=document.createElement("script");return e.setAttribute("src",r),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function Ko(r,t=!1){if(!fr)throw new Error("Cannot load script in server environment");let e=hu(r)??gu(r,t);return new Promise((a,i)=>{e.onload=()=>{a()},e.onerror=()=>{i(new Error(`Failed to load script: ${r}`))},e.parentNode||document.head.appendChild(e)})}var X={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Me=r=>(...t)=>({_$litDirective$:r,values:t}),Fe=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,a){this._$Ct=t,this._$AM=e,this._$Ci=a}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};var Sa=class extends Fe{constructor(t){if(super(t),this.it=g,t.type!==X.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===g||t==null)return this._t=void 0,this.it=t;if(t===re)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;let e=[t];return e.raw=e,this._t={_$litType$:this.constructor.resultType,strings:e,values:[]}}};Sa.directiveName="unsafeHTML",Sa.resultType=1;var Vo=Me(Sa);var Uo=Symbol.for("primer-sdk-core-dialog-access");function Fo(r){return{token:Uo,content:r}}function Oi(r){return r!==void 0&&r.token===Uo&&typeof r.content=="string"}var Ho=f` :host { display: block; } .content-container { width: 100%; height: 100%; display: flex; flex-direction: column; background-color: var(--primer-color-background-outlined-default); } .error { display: flex; align-items: center; justify-content: center; padding: var(--primer-space-large); color: var(--primer-color-text-danger); font-family: var(--primer-typography-body-medium-font); font-size: var(--primer-typography-body-medium-size); } `;var ce=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.open=!1}openDialog(){this.open=!0}closeDialog(){let e=document.querySelector("primer-dialog");if(e){e.startExitAnimation();let a=()=>{this.open=!1,this.removeEventListener("primer-dialog-close",a)};this.addEventListener("primer-dialog-close",a)}else this.open=!1}renderContent(){return p`<div class="content-container"><slot></slot>${this.renderSecureHtmlContent()}</div>`}renderSecureHtmlContent(){return this.secureHtmlContent?Oi(this.secureHtmlContent)?p`${Vo(this.secureHtmlContent.content)}`:(E.warn("PortalDialogComponent: Invalid access token provided for htmlContent. Content will not be rendered."),g):g}renderDialog(){return this.open?p`<primer-portal><primer-dialog .open=${this.open} size=${this.size} .showCloseButton=${!1} @primer-dialog-close="${()=>this.closeDialog()}" >${this.renderContent()}</primer-dialog></primer-portal>`:g}connectedCallback(){super.connectedCallback(),this.open||this.openDialog()}updated(e){if(super.updated(e),e.has("secureHtmlContent")){let a=this.secureHtmlContent;a&&!Oi(a)&&(E.errorWithDatadog("PortalDialogComponent: Invalid access token provided for htmlContent. Content will not be rendered."),this.secureHtmlContent=void 0)}e.has("open")&&this.open&&this.onOpen&&this.onOpen(),e.has("open")&&this.open&&this.onContentRendered&&this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.onContentRendered?.()})})}render(){return p`${this.renderDialog()}`}};ce.styles=[k,Ho],d([u({type:String})],ce.prototype,"size",2),d([u({type:Boolean})],ce.prototype,"showCloseButton",2),d([u({type:Object})],ce.prototype,"onOpen",2),d([u({type:Object})],ce.prototype,"onContentRendered",2),d([u({type:Object,converter:{fromAttribute:()=>{},toAttribute:()=>null}})],ce.prototype,"secureHtmlContent",2),d([P()],ce.prototype,"open",2),ce=d([S("primer-portal-dialog"),B()],ce);var vr=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let a=Fo(t.htmlContent),i=new ce;i.secureHtmlContent=a,i.size="large",i.showCloseButton=!1,i.onContentRendered=t.onContentReady;let n=()=>{this.currentDialog=null,this.currentResolver=null,e({success:!1})};i.addEventListener("primer-dialog-close",n),this.currentDialog=i,this.currentResolver=e,document.body.appendChild(i)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}};var Gi="0.8.2",Sr=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 D(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()}),new D(t,{args:()=>[this.sdkInstanceTask.value,this.paymentsList],task:this.initializeLitContext()})}set paymentsList(t){this._paymentsList=t,this.host.requestUpdate()}get paymentsList(){return this._paymentsList}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkStateController.startLoading(),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.getAnalyticsUtils()){let e=this.host.sdkStateController.currentState;(e.isProcessing||e.isLoading||this.currentSdkInstance)&&Q({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}normalizeOptionsForLegacySdk(t){if(t.sdkCore!==!1)return t.sdkCore=!0,t;let e={...t};if(e.card?.cardholderName){let a={...e.card.cardholderName};a.visible===!1&&(a.required=!1),e.card={...e.card,cardholderName:a}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkStateController.currentState.isLoading&&(E.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkStateController.completeLoading())},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.paymentsList=[],this.createPaymentMethodManager=null,this.host.sdkStateController.reset(),this.currentSdkInstance.teardown?.(),E.info("SDK instance cleaned up")}catch(t){E.errorWithDatadog("Error cleaning up SDK instance",{error:t})}so(),E.setClientToken(void 0),E.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=Go){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){E.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await Ko(t),await e.Primer.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return E.warn("Component disconnected, aborting SDK initialization"),_;if(!t||!e)return _;this.cleanupResources();let a;try{let i;if(e.sdkCore!==!1){let l=new vr;i={createHeadless:(m,y)=>Yn(m,{...y,dialogProvider:l,sdkVersion:Gi})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new gr(null);let n=this.normalizeOptionsForLegacySdk(e);E.setClientToken(t),E.setSdkOptions(n);let o=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:l=>{this.isDisconnected||(E.info("Configuration payment methods:",l),this.paymentsList=l)},onCheckoutComplete:({payment:l})=>{if(this.isDisconnected)return;E.info("Payment completed:",l);let c=l?.paymentMethodData?.paymentMethodType||"UNKNOWN";if(this.host.sdkStateController.completeProcessing(),l&&this.host.primerEventsController.dispatchPaymentSuccess(l,c),Q({eventName:"PAYMENT_SUCCESS",paymentId:l?.id}),this.primerJS?.onPaymentSuccess&&l){let m=Math.floor(Date.now()/1e3);this.primerJS.onPaymentSuccess({payment:Ut(l),paymentMethodType:c,timestamp:m})}},onCheckoutFail:(l,c)=>{if(this.isDisconnected)return;(C=>typeof C=="object"&&C!==null&&"response"in C&&typeof C.response=="object"&&C.response!==null&&"status"in C.response&&typeof C.response.status=="number")(l)&&l.response.status>=500?E.errorWithDatadog("Payment failed with server error",{error:l}):E.error("Payment failed:",l);let h=c.payment?.paymentMethodData?.paymentMethodType||"UNKNOWN",A=l instanceof yr?{code:l.code||"UNKNOWN_ERROR",message:l.message||"Unknown error occurred",diagnosticsId:l.diagnosticsId,data:l.data}:(()=>{let C=l,T=C instanceof Error&&"code"in C&&typeof C.code=="string"?C.code:"UNKNOWN_ERROR",N=C instanceof Error?C.message:"Unknown error occurred";return{code:T,message:N,data:{error:l}}})();if(this.host.sdkStateController.setPaymentFailure(A),this.host.primerEventsController.dispatchPaymentFailure({code:A.code,message:A.message,diagnosticsId:"diagnosticsId"in A?A.diagnosticsId??void 0:void 0,data:A.data},h,c.payment),Q({eventName:"PAYMENT_FAILURE",paymentId:c.payment?.id}),this.primerJS?.onPaymentFailure){let C=Math.floor(Date.now()/1e3);this.primerJS.onPaymentFailure({error:{code:A.code,message:A.message,diagnosticsId:"diagnosticsId"in A?A.diagnosticsId??void 0:void 0,data:A.data},payment:c.payment?Ut(c.payment):void 0,paymentMethodType:h,timestamp:C})}},onBeforePaymentCreate:(l,c)=>{if(this.isDisconnected)return;this.host.sdkStateController.currentState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:l.paymentMethodType}),this.host.sdkStateController.startProcessing(),this.primerJS?this.primerJS.handleBeforePaymentCreate(l,c):c?.continuePaymentCreation()},onPaymentMethodAction:(l,c)=>{this.isDisconnected||l==="PAYMENT_METHOD_UNSELECTED"&&this.host.sdkStateController.stopProcessing()},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.createPaymentMethodManager=o.createPaymentMethodManager.bind(o),this.currentSdkInstance=o,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:o,writable:!1}),await o.start(),this.isDisconnected)return this.cleanupResources(),_;this.host.sdkContextController.setClientOptions(e),this.primerJS&&this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS);let s=o.getSDKUtilities();if(a=o.getAnalyticsUtils?.(),a&&(this.host.sdkContextController.setAnalyticsUtils({...a,sdkVersion:Gi}),oo({environment:a.environment,checkoutSessionId:a.checkoutSessionId,clientSessionId:a.clientSessionId||"",primerAccountId:a.primerAccountId||"",sdkVersion:Gi,clientSessionToken:a.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),Q({eventName:"SDK_INIT_START"})),this.host.sdkContextController.setHeadlessUtils(s),e.sdkCore&&o.getConfiguration){let l=o.getConfiguration();this.host.sdkContextController.setConfiguration(l)}return this.host.vaultManagerController.initializeVaultManager(o.createVaultManager.bind(o),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!s.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState}),o}catch(i){throw i instanceof Error&&(E.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkStateController.setPrimerJsError(i)),this.cleanupResources(),i}}}initializeLitContext(){return async([t,e])=>{if(this.isDisconnected)return _;if(!t||!e.length)return _;let a=new Map,i=new Map;try{for(let o of e){if(this.isDisconnected)break;let s=await this.initializePaymentMethodManager(o)();o&&s&&(a.set(o.type,o),i.set(o.type,s))}if(this.isDisconnected)return _;let n=new Qa(a);return this.host.sdkContextController.setPaymentManagers(i),this.host.sdkContextController.setPaymentMethods(n),this.primerJS&&(this.primerJS.setPaymentMethods(n),this.primerJS.setPaymentManagers(i)),this.host.primerEventsController.dispatchPaymentMethods(n),E.info("Initialized payment methods:",n.toArray()),a}catch(n){if(n instanceof Error)throw this.host.sdkStateController.setPrimerJsError(n),n;return null}finally{this.clearLoadingTimeout(),this.isDisconnected||(this.host.sdkStateController.completeLoading(),Q({eventName:"SDK_INIT_END"}))}}}initializePaymentMethodManager(t){let{type:e,managerType:a}=t;return async()=>{if(this.isDisconnected||!this.createPaymentMethodManager)return null;if(a==="KLARNA"){let i=await this.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:n=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:n,isLoading:!1})}});return i?{type:e,manager:i}:null}try{if(a==="CARD"){let n=await this.createPaymentMethodManager("PAYMENT_CARD",{onCardNetworksChange:o=>{this.isDisconnected||this.host.cardNetworkController.processCardNetworkChangeEvent(o)},onCardNetworksLoading:()=>{this.isDisconnected||this.host.cardNetworkController.setCardNetworksLoading()}});return n?{type:e,manager:n}:null}let i=await this.createPaymentMethodManager(e);return i?{type:e,manager:i}:null}catch(i){return E.errorWithDatadog(`Failed to initialize manager for ${e}`,{error:i}),null}}}};var br=class{constructor(t){this.host=t,t.addController(this)}_error(t){let{error:e}=t.detail;this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:e.message})}_mandateConfirmed(){this.host.sdkStateController.completeProcessing()}_mandateDeclined(){this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:"Mandate declined"})}hostConnected(){this.host.addEventListener("primer-ach-error",this._error.bind(this)),this.host.addEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.addEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}hostDisconnected(){this.host.removeEventListener("primer-ach-error",this._error.bind(this)),this.host.removeEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.removeEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}};var yu=qi({"../../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")});Ti(r=>yu(`../../localization/lit-localize/locales/${r}.ts`));var fu={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},Ee=class extends v{constructor(){super();this.customStyles="";this.clientToken="";this.options={};this.disableLoader=!1;this._jsInitialized=!1;this.previousLoadingState=!0;this.hasAssignedContent=!1;this._loadingTimeoutId=null;this._eventListenerController=null;this.locale="en-GB";this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new $a(this),this.sdkStateController=new Ya(this),this.primerEventsController=new Ft(this),this.styleProcessingController=new za(this),this.vaultManagerController=new ia(this),this.cardNetworkController=new Ma(this),this.achPaymentEventsController=new br(this),this.headlessSdkController=new Sr(this)}set jsInitialized(e){this.requestUpdate(),this._jsInitialized=e}get jsInitialized(){return this._jsInitialized}get primerJS(){return this.headlessSdkController?.primerJSInstance??void 0}connectedCallback(){super.connectedCallback(),this.sdkContextController.setEventsController(this.primerEventsController),this._eventListenerController=new AbortController,document.addEventListener("primer:card-submit",this.handleExternalCardSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:vault-submit",this.handleExternalVaultSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:show-other-payments-toggle",this.handleExternalShowOtherPaymentsToggle.bind(this),{signal:this._eventListenerController.signal})}attributeChangedCallback(e,a,i){e===fu.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,a,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkStateController?.currentState.isLoading&&this.sdkStateController.forceCompleteLoading(),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(Ni(this.options?.locale)?this.locale=Ii(this.options?.locale):E.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to default locale `en-GB`")),Pi(this.locale||"en-GB"))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}handleExternalCardSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:card-submit",e.detail)}handleExternalVaultSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:vault-submit",e.detail)}handleExternalShowOtherPaymentsToggle(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:show-other-payments-toggle",e.detail)}checkLoadingStateChange(){let e=this.sdkStateController?.currentState.isLoading||!1;this.previousLoadingState&&!e&&(this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"})),this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkStateController?.currentState.isLoading&&(E.warn("Loading timeout in component, forcing completion"),this.sdkStateController.forceCompleteLoading(),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkStateController.currentState,a=e.isLoading,i=e.primerJsError,n=!a&&!i;return p` ${L(a,()=>g)} ${L(i,()=>p`<primer-checkout-error></primer-checkout-error>`)} ${L(n,()=>p`<slot name="main" @slotchange=${this.onSlotChange}></slot>${L(this.hasAssignedContent,()=>g,()=>p`<primer-main></primer-main>`)} `,()=>g)} `}addEventListener(e,a,i){super.addEventListener(e,a,i)}removeEventListener(e,a,i){super.removeEventListener(e,a,i)}};Ee.styles=[k,Oo],d([u({type:String,attribute:"custom-styles"})],Ee.prototype,"customStyles",2),d([u({type:String,attribute:"client-token"})],Ee.prototype,"clientToken",2),d([u({type:Object})],Ee.prototype,"options",2),d([u({type:Boolean,attribute:"loader-disabled"})],Ee.prototype,"disableLoader",2),d([u({type:Boolean,reflect:!0,attribute:"js-initialized"})],Ee.prototype,"_jsInitialized",2),d([Ue("slot")],Ee.prototype,"defaultSlot",2),d([P()],Ee.prototype,"previousLoadingState",2),Ee=d([B(),S("primer-checkout")],Ee);function vu(r){return document.querySelector(`#${r}`)}function Su(r,t){let e=document.createElement("style");return e.textContent=r,e.id=t,e}function ba(r,t,e=!0){if(!fr||vu(t))return;let i=Su(r,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var Yo=`
154
154
  @keyframes primer-css-spinner-rotate {
155
155
  0% {
156
156
  transform: rotate(0deg);
@@ -207,4 +207,4 @@ primer-checkout:not([js-initialized]):not([loader-disabled])::after {
207
207
  input[data-custom-input]:focus {
208
208
  outline: none;
209
209
  }
210
- `,t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}function Rl(r,t){return r.active!==t.active||r.dirty!==t.dirty||r.error!==t.error||r.errorCode!==t.errorCode||r.submitted!==t.submitted||r.touched!==t.touched||r.valid!==t.valid}var _r=class{constructor(t,e){this._meta={active:!1,dirty:!1,error:null,errorCode:null,submitted:!1,touched:!1,valid:!1};this._hostedInput=null;this._standardInput=null;this.host=t,this.config=e,this.host.addController(this),this.setupTask=new D(this.host,{args:()=>[this.getHostedInput()],task:this.setupHostedInput.bind(this)}),this.host.addEventListener("wrapper-click",()=>{this.focusInput()})}focusInput(){this._hostedInput?this._hostedInput.focus():this._standardInput&&this._standardInput.focus()}notifyUserInteraction(){let t=this.host.cardFormContext;t?.onUserInteraction&&t.onUserInteraction()}getHostedInput(){let{type:t}=this.config,e=this.host.cardFormContext;return e?{cardNumber:e.cardNumberInput,cvv:e.cvvInput,expire:e.expiryInput,cardholderName:e.cardholderNameInput??"cardholderName"}[t]:void 0}async setupHostedInput([t]){if(!t)return _;await this.host.updateComplete;let e=this.getTargetContainer();return e?t==="cardholderName"?this.setupStandardInput(e):this.setupHostedIframeInput(t,e):_}getTargetContainer(){return this.host.renderRoot.querySelector(this.config.containerSelector)}setupStandardInput(t){let e=document.createElement("input");return e.type="text",e.placeholder=this.host.placeholder,Ll(e,this.host),(this.host.ariaLabel||this.host.label)&&e.setAttribute("aria-label",this.host.ariaLabel??this.host.label),this.setupInputEventListeners(e),t.innerHTML="",t.appendChild(e),this._standardInput=e,!0}setupInputEventListeners(t){t.addEventListener("input",e=>{let a=e.target,n=!!a.value.trim();this.notifyUserInteraction(),this._meta={...this._meta,dirty:n},this.config.onInput?.(a.value),this.host.requestUpdate()}),t.addEventListener("focus",()=>{this.notifyUserInteraction(),this._meta.active=!0,this.host.requestUpdate()}),t.addEventListener("blur",()=>{this._meta.active=!1,this._meta.touched=!1,this.host.requestUpdate()}),t.addEventListener("keydown",e=>{if(e.key==="Enter"){e.preventDefault();let a=this.host.closest("form");a&&a.requestSubmit()}})}async setupHostedIframeInput(t,e){await new Promise(n=>requestAnimationFrame(()=>n())),this._hostedInput=t;let a=xr(this.host.computedStyles),i=a?{style:{input:{base:a}}}:void 0;return t.addEventListener("focus",()=>{this.notifyUserInteraction(),this._meta.active=!0,this.host.requestUpdate()}),t.addEventListener("blur",()=>{this._meta.active=!1,this.host.requestUpdate()}),t.addEventListener("change",n=>{let o=n;this.notifyUserInteraction(),Rl(this._meta,o)&&(this._meta={...this._meta,...o},this.host.requestUpdate())}),t.addEventListener("enter",()=>{let n=this.host.closest("form");n&&n.requestSubmit()}),await t.render(e,{placeholder:this.host.placeholder,ariaLabel:this.host.ariaLabel,...i}),!0}get meta(){return this._meta}updateMetaFromValidation(t){this._meta={...this._meta,valid:!!t.valid,error:t.error||null,errorCode:t.errorCode||null},this.host.requestUpdate()}setSubmitted(t){this._meta={...this._meta,submitted:t,...t&&{touched:!0}},this.host.requestUpdate()}hostConnected(){this.registerWithContext()}hostDisconnected(){this.unregisterFromContext(),this._hostedInput=null,this._standardInput=null}registerWithContext(){let t=this.host.cardFormContext;t?.registerInputController&&t.registerInputController(this.config.type,this)}unregisterFromContext(){let t=this.host.cardFormContext;t?.unregisterInputController&&t.unregisterInputController(this.config.type)}};var xl=f` :host { display: contents; } form { display: flex; flex-direction: column; gap: var(--primer-space-medium); width: 100%; } .card-form { display: flex; flex-direction: column; gap: var(--primer-space-medium); margin-bottom: var(--primer-space-medium); } .card-form-row { display: flex; gap: var(--primer-space-small); } `;var _l={cardholderName:"cardholderName",cardNumber:"cardNumber",cardExpiryDate:"expire",expiryDate:"expire",cardSecurityCode:"cvv",cvv:"cvv"},te=class extends v{constructor(){super(...arguments);this.hideLabels=!1;this.disabled=!1;this.hasAssignedContent=!1;this.selectedCardNetwork=null;this.formErrorMessage=null;this.paymentMethodSelectionSent=!1;this.paymentManagers=new Map;this.clientOptions=null;this.headlessUtils=null;this.analyticsUtils=null;this.contextEventsController=null;this.cardFormProvider=new $(this,{context:Zt,initialValue:null});this.eventsController=new Ft(this);this._contextCardSubmitListener=null;this._isHandlingContextEvent=!1;this.inputControllers=new Map;this.setupCardFormTask=new D(this,{task:([e])=>{if(!e?.manager)return _;let{manager:a}=e,i=a.createHostedInputs(),{cardNumberInput:n,expiryInput:o,cvvInput:s}=i;return this.cardFormProvider.setValue({cardholderNameInput:i.cardholderNameInput,cardNumberInput:n,expiryInput:o,cvvInput:s,setCardholderName:l=>{a.setCardholderName(l),this.shouldRequireCardholderName&&a.validate?.().then(c=>{let y=c?.validationErrors?.find(A=>A.name===_l.cardholderName),h=this.inputControllers.get("cardholderName");h&&h.updateMetaFromValidation({valid:!1,error:y?.message||y?.error||null,errorCode:y?.message||y?.error||null})})},setCardNetwork:l=>{this.selectedCardNetwork=l},validate:()=>a.validate(),submit:l=>a.submit(l),hideLabels:this.hideLabels,disabled:this.disabled,setSubmissionState:l=>{this.inputControllers.forEach(c=>{c.setSubmitted(l)})},propagateValidationErrors:l=>{l&&l.forEach(c=>{let m=c.field||c.name,y=c.message||c.error,h=_l[m];if(h){let A=this.inputControllers.get(h);if(A){let C={valid:!1,error:y,errorCode:y};A.updateMetaFromValidation(C)}}})},registerInputController:(l,c)=>{this.inputControllers.set(l,c)},unregisterInputController:l=>{this.inputControllers.delete(l)},onUserInteraction:()=>{this.sendPaymentMethodSelectionEvent(),this.checkAndSendPaymentDetailsEnteredEvent()}}),!0},args:()=>[this.paymentManagers.get("PAYMENT_CARD")]});this.paymentDetailsEnteredSent=!1;this.handleSlotButtonClick=e=>{let i=e.target.closest("button, primer-button");if(!i)return;let n=i;this.isSubmitButton(n)&&(e.preventDefault(),this.submitCardPayment())};this.handleDirectSubmit=e=>{e.stopPropagation(),this.submitCardPayment()};this.handleContextCardSubmit=e=>{if(!this._isHandlingContextEvent){this._isHandlingContextEvent=!0;try{e.target!==this&&(e.stopPropagation(),this.submitCardPayment())}finally{this._isHandlingContextEvent=!1}}};this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0};this.handleFormSubmit=e=>{e.preventDefault(),e.stopPropagation(),this.submitCardPayment()}}updated(e){if(super.updated(e),(e.has("hideLabels")||e.has("disabled"))&&this.cardFormProvider.value&&this.cardFormProvider.setValue({...this.cardFormProvider.value,hideLabels:this.hideLabels,disabled:this.disabled}),e.has("contextEventsController")){let a=e.get("contextEventsController");a?.host&&this._contextCardSubmitListener&&a.host.removeEventListener("primer:card-submit",this._contextCardSubmitListener),this.setupContextEventListeners()}}get shouldShowCardholderName(){let e=this.clientOptions?.card?.cardholderName;return typeof e?.visible=="boolean"?e.visible:!0}get shouldRequireCardholderName(){if(!this.shouldShowCardholderName)return!1;let e=this.clientOptions?.card?.cardholderName;return typeof e?.required=="boolean"?e.required:!0}sendPaymentMethodSelectionEvent(){this.paymentMethodSelectionSent||(this.paymentMethodSelectionSent=!0,Q({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYMENT_CARD"}))}checkAndSendPaymentDetailsEnteredEvent(){if(this.paymentDetailsEnteredSent)return;let e=this.inputControllers.get("cardNumber"),a=this.inputControllers.get("expire"),i=this.inputControllers.get("cvv"),n=e?.meta?.dirty===!0,o=a?.meta?.dirty===!0,s=i?.meta?.dirty===!0,l=!0;this.shouldRequireCardholderName&&(l=this.inputControllers.get("cardholderName")?.meta?.dirty===!0),n&&o&&s&&l&&(this.sendPaymentDetailsEnteredEvent(),this.paymentDetailsEnteredSent=!0)}sendPaymentDetailsEnteredEvent(){Q({eventName:"PAYMENT_DETAILS_ENTERED",paymentMethod:"PAYMENT_CARD"})}connectedCallback(){super.connectedCallback(),this.addEventListener("click",this.handleSlotButtonClick),this.addEventListener("primer:card-submit",this.handleDirectSubmit),this._contextCardSubmitListener=e=>{this.handleContextCardSubmit(e)},this.setupContextEventListeners()}disconnectedCallback(){this.removeEventListener("click",this.handleSlotButtonClick),this.removeEventListener("primer:card-submit",this.handleDirectSubmit),this.cleanupContextEventListeners(),super.disconnectedCallback()}setupContextEventListeners(){this.contextEventsController?.host&&this._contextCardSubmitListener&&this.contextEventsController.host.addEventListener("primer:card-submit",this._contextCardSubmitListener)}cleanupContextEventListeners(){this.contextEventsController?.host&&this._contextCardSubmitListener&&this.contextEventsController.host.removeEventListener("primer:card-submit",this._contextCardSubmitListener)}isSubmitButton(e){let a=e.tagName.toLowerCase(),i=a==="button",n=a==="primer-button";return i&&(e.getAttribute("type")==="submit"||e.hasAttribute("data-submit"))||n&&(e.getAttribute("type")==="submit"||e.hasAttribute("data-submit"))}async submitCardPayment(){let e=this.cardFormProvider.value;if(!e||this.disabled)return;this.formErrorMessage=null,e.setSubmissionState?.(!0);let a=this.querySelector("primer-billing-address")||this.renderRoot.querySelector("primer-billing-address"),i=!0;a&&(i=await a.validateForSubmission());let n=await e.validate?.();if(n?.valid&&i){if(a&&!await a.submitToSDK()){let c=b("tokenizationError",{id:"tokenizationError"});this.formErrorMessage=c,this.eventsController.dispatchFormSubmitErrors([{field:"billingAddress",name:"billingAddress",error:"BILLING_ADDRESS_SUBMISSION_FAILED",message:c}]);return}let o=this.selectedCardNetwork?{cardNetwork:this.selectedCardNetwork}:void 0;await e.submit?.(o);let s={success:!0};this.eventsController.dispatchFormSubmitSuccess(s)}else{let o=n?.validationErrors;e.propagateValidationErrors?.(o||[]),this.cardFormProvider.setValue({...e,errors:o}),this.eventsController.dispatchFormSubmitErrors(o)}}render(){return this.setupCardFormTask.status===yt.ERROR||this.setupCardFormTask.status===yt.INITIAL?g:p`<form @submit=${this.handleFormSubmit}><slot name="card-form-content" @slotchange=${this.onSlotChange}></slot>${this.setupCardFormTask.render({complete:()=>L(this.hasAssignedContent,()=>g,()=>p`<div class="card-form"><primer-input-card-number></primer-input-card-number><div class="card-form-row"><primer-input-card-expiry></primer-input-card-expiry><primer-input-cvv></primer-input-cvv></div>${L(this.shouldShowCardholderName,()=>p`<primer-input-card-holder-name></primer-input-card-holder-name>`,()=>g)}<primer-billing-address></primer-billing-address></div><primer-card-form-submit></primer-card-form-submit><primer-error-message message="${this.formErrorMessage||""}" ?visible="${!!this.formErrorMessage}" ></primer-error-message>`)})}</form>`}};te.styles=[k,xl],d([u({type:Boolean,attribute:"hide-labels",reflect:!0})],te.prototype,"hideLabels",2),d([u({type:Boolean,attribute:"disabled"})],te.prototype,"disabled",2),d([P()],te.prototype,"hasAssignedContent",2),d([P()],te.prototype,"selectedCardNetwork",2),d([P()],te.prototype,"formErrorMessage",2),d([M({context:z,subscribe:!0}),u({type:Object})],te.prototype,"paymentManagers",2),d([M({context:he}),u({attribute:!1})],te.prototype,"clientOptions",2),d([M({context:Y,subscribe:!0}),u({attribute:!1})],te.prototype,"headlessUtils",2),d([M({context:mt,subscribe:!0}),u({attribute:!1})],te.prototype,"analyticsUtils",2),d([M({context:Ge,subscribe:!0}),u({attribute:!1})],te.prototype,"contextEventsController",2),te=d([S("primer-card-form"),B()],te);var ue=class extends v{constructor(){super();this._cardFormContext=null;this.computedStyles=null;this._userAssignedProps=new Set;this._internalLabel="";this._internalPlaceholder="";this._internalAriaLabel="";this.handleWrapperClick=()=>{this.hostedInputController.focusInput()};this.hostedInputController={}}get cardFormContext(){return this._cardFormContext}set cardFormContext(e){let a=this._cardFormContext;this._cardFormContext=e,!a&&e&&this.updateComplete.then(()=>{this.hostedInputController?.registerWithContext?.()}),this.requestUpdate("cardFormContext",a)}getTranslatedValue(e){return e?typeof e=="string"?e:b(e.id,{id:e.id}):""}get label(){return this._userAssignedProps.has("label")?this._internalLabel:this.getTranslatedValue(this.config.translations.label)}set label(e){let a=this.label;e!==""?(this._userAssignedProps.add("label"),this._internalLabel=e):(this._userAssignedProps.delete("label"),this._internalLabel=""),this.requestUpdate("label",a)}get placeholder(){return this._userAssignedProps.has("placeholder")?this._internalPlaceholder:this.getTranslatedValue(this.config.translations.placeholder)}set placeholder(e){let a=this.placeholder;this._userAssignedProps.add("placeholder"),this._internalPlaceholder=e,this.requestUpdate("placeholder",a)}get ariaLabel(){return this._userAssignedProps.has("ariaLabel")?this._internalAriaLabel:this.getTranslatedValue(this.config.translations.ariaLabel)||this.getTranslatedValue(this.config.translations.label)}set ariaLabel(e){let a=this.ariaLabel;e!==""?(this._userAssignedProps.add("ariaLabel"),this._internalAriaLabel=e):(this._userAssignedProps.delete("ariaLabel"),this._internalAriaLabel=""),this.requestUpdate("ariaLabel",a)}childUpdated(){Object.defineProperty(this,"hostedInputController",{value:new _r(this,{type:this.config.inputType,containerSelector:this.config.containerSelector,onInput:this.config.onInput}),writable:!1,configurable:!1})}getError(){let e=this.hostedInputController.meta;return e.submitted||e.dirty&&e.touched?e.errorCode:null}renderInput(){if(this.hostedInputController.setupTask.status===yt.ERROR)return g;let e=this.getError();return p`<primer-input-wrapper .focusWithin="${this.hostedInputController.meta.active}" .hasError=${!!e} @wrapper-click="${this.handleWrapperClick}" >${L(!this.cardFormContext?.hideLabels,()=>p`<primer-input-label slot="label" >${this.label}</primer-input-label >`,()=>g)}<div slot="input" class="card-input-slot" id="${this.config.containerSelector.substring(1)}" aria-label="${this.ariaLabel}" ></div>${L(e,()=>p`<primer-input-error slot="error">${b(e,{id:e})}</primer-input-error>`,()=>g)}</primer-input-wrapper>`}};d([M({context:Zt,subscribe:!0})],ue.prototype,"cardFormContext",1),d([M({context:Yt,subscribe:!0}),u()],ue.prototype,"computedStyles",2),d([u({type:String})],ue.prototype,"label",1),d([u({type:String})],ue.prototype,"placeholder",1),d([u({type:String,attribute:"aria-label"})],ue.prototype,"ariaLabel",1);var wl=f` :host { display: contents; } .card-number-container { display: flex; align-items: center; width: 100%; position: relative; gap: var(--primer-space-small); } #cardNumber { flex: 1; display: flex; width: 100%; } .network-selector-container { display: flex; align-items: center; z-index: 2; } `;var At=f` .card-input-slot { display: flex; } `;var ot=class extends ue{constructor(){super();this.config={inputType:"cardNumber",containerSelector:"#cardNumber",errorName:"cardNumber-card",translations:{label:{id:"cardNumber",defaultMessage:"Card Number"},placeholder:"4111 1111 1111 1111",ariaLabel:{id:"cardNumber",defaultMessage:"Card Number"}}};this.handleNetworkSelected=e=>{let{network:a}=e.detail;this.cardFormContext&&this.cardFormContext.setCardNetwork(a)};this.childUpdated()}renderInput(){if(this.hostedInputController.setupTask.status===yt.ERROR)return g;let e=this.getError();return p`<primer-input-wrapper .focusWithin="${this.hostedInputController.meta.active}" .hasError=${!!e} >${L(!this.cardFormContext?.hideLabels,()=>p`<primer-input-label slot="label" >${this.label}</primer-input-label >`,()=>g)}<div slot="input" class="card-number-container" aria-label="${this.ariaLabel}" ><div id="${this.config.containerSelector.substring(1)}"></div><div class="network-selector-container"><primer-card-network-selector @network-selected=${this.handleNetworkSelected} ></primer-card-network-selector></div></div>${L(e,a=>p`<primer-input-error slot="error">${b(a,{id:a})}</primer-input-error>`,()=>g)}</primer-input-wrapper>`}render(){return this.renderInput()}};ot.styles=[k,At,wl],ot=d([S("primer-input-card-number"),B()],ot);var Bl=f` :host { display: contents; } `;var st=class extends ue{constructor(){super();this.config={inputType:"cvv",containerSelector:"#cvv",errorName:"cvv-card",translations:{label:"CVV",placeholder:"123"}};this.childUpdated()}render(){return this.renderInput()}};st.styles=[k,At,Bl],st=d([S("primer-input-cvv"),B()],st);var Dl=f` :host { display: contents; } `;var lt=class extends ue{constructor(){super();this.config={inputType:"expire",containerSelector:"#expiry",errorName:"expiryDate-card",translations:{label:{id:"cardExpiry",defaultMessage:"Expiry Date"},placeholder:{id:"cardExpiryPlaceholder",defaultMessage:"MM/YY"},ariaLabel:{id:"cardExpiry",defaultMessage:"Expiry Date"}}};this.childUpdated()}render(){return this.renderInput()}};lt.styles=[k,At,Dl],lt=d([S("primer-input-card-expiry"),B()],lt);var Ol=f` :host { display: contents; } `;var dt=class extends ue{constructor(){super();this.config={inputType:"cardholderName",containerSelector:"#cardFormName",errorName:"cardholderName",translations:{label:{id:"cardholderNameLabel",defaultMessage:"Cardholder Name"},placeholder:{id:"cardholderNamePlaceholder",defaultMessage:"Name on card"},ariaLabel:{id:"cardholderNameLabel",defaultMessage:"Cardholder Name"}},onInput:e=>this.handleInput(e)};this.childUpdated()}handleInput(e){this.cardFormContext?.setCardholderName?.(e)}render(){return this.renderInput()}};dt.styles=[k,At,Ol],dt=d([S("primer-input-card-holder-name"),B()],dt);var Gl=f` :host { display: contents; } `;var Z=class extends v{constructor(){super(...arguments);this._userAssignedProps=new Set;this._internalButtonText="";this.headlessUtils=null;this.clientOptions=null;this.sdkState=null;this.cardFormContext=null;this.analyticsUtils=null;this.contextEventsController=null;this.variant="primary";this.disabled=!1;this.handleClick=e=>{if(e.preventDefault(),this.disabled)return;Q({eventName:"PAYMENT_SUBMITTED",paymentMethod:"PAYMENT_CARD"});let a=new CustomEvent("primer:card-submit",{bubbles:!0,composed:!0,detail:{source:"primer-card-form-submit"}});this.dispatchEvent(a)}}get buttonText(){return this._userAssignedProps.has("buttonText")?this._internalButtonText:b("pay",{id:"pay"})}set buttonText(e){let a=this.buttonText;e!==""?(this._userAssignedProps.add("buttonText"),this._internalButtonText=e):(this._userAssignedProps.delete("buttonText"),this._internalButtonText=""),this.requestUpdate("buttonText",a)}get submitButtonConfig(){return this.clientOptions?.submitButton??null}get shouldShowBuiltInButton(){return this.submitButtonConfig?.useBuiltInButton??!0}render(){if(!this.shouldShowBuiltInButton)return g;let e=this.submitButtonConfig?.amountVisible?this.headlessUtils?.getUIOrderAmount():null,a=e?` ${e}`:g,i=this.disabled||this.cardFormContext?.disabled||!1;return p`<primer-button type="submit" variant=${this.variant} ?disabled=${i} @click=${this.handleClick} .loading=${!!this.sdkState?.isProcessing} data-submit >${this.buttonText}${a}</primer-button>`}};Z.styles=[k,Gl],d([u({type:String})],Z.prototype,"buttonText",1),d([M({context:Y,subscribe:!0}),u({type:Object})],Z.prototype,"headlessUtils",2),d([M({context:he,subscribe:!0}),u({type:Object})],Z.prototype,"clientOptions",2),d([M({context:j,subscribe:!0}),u()],Z.prototype,"sdkState",2),d([M({context:Zt,subscribe:!0}),u()],Z.prototype,"cardFormContext",2),d([M({context:mt,subscribe:!0}),u({attribute:!1})],Z.prototype,"analyticsUtils",2),d([M({context:Ge,subscribe:!0}),u({attribute:!1})],Z.prototype,"contextEventsController",2),d([u({type:String})],Z.prototype,"variant",2),d([u({type:Boolean})],Z.prototype,"disabled",2),Z=d([S("primer-card-form-submit"),B()],Z);var Kl=f` :host { display: flex; align-items: center; position: relative; } .network-selector { display: flex; align-items: center; cursor: pointer; background: none; padding: unset; border: none; transition: opacity var(--primer-animation-duration) var(--primer-animation-easing); outline: none; gap: var(--primer-space-xsmall); } .network-selector:hover { opacity: 0.8; } .network-selector:focus-visible { outline: 2px solid var(--primer-color-focus); border-radius: var(--primer-radius-xsmall); } .network-icon { width: var(--primer-size-large); height: var( --primer-size-medium ); /* Added explicit height to maintain aspect ratio */ object-fit: contain; } .caret { margin-left: var(--primer-space-xsmall); transition: transform var(--primer-animation-duration) var(--primer-animation-easing); color: var(--primer-color-icon-primary); } .caret.open { transform: rotate(180deg); } .dropdown { position: absolute; top: 100%; right: 0; width: max-content; min-width: calc(var(--primer-size-xxxlarge) * 3); background: var(--primer-color-gray-000); border-radius: var(--primer-radius-small); box-shadow: 0 var(--primer-space-xxsmall) var(--primer-space-large) rgba(0, 0, 0, 0.15); z-index: 10; overflow: hidden; border: 1px solid var(--primer-color-border-outlined-default); } .dropdown:not(.open) { display: none; } .dropdown.open { display: block; max-height: calc(var(--primer-size-xxxlarge) * 4); overflow-y: auto; } .network-option { display: flex; align-items: center; padding: var(--primer-space-small) var(--primer-space-medium); cursor: pointer; transition: background-color var(--primer-animation-duration) var(--primer-animation-easing); position: relative; outline: none; background-color: transparent; } /* Only apply hover effect when not in keyboard navigation mode */ .network-option:hover { background-color: var(--primer-color-gray-100); } /* Apply focused style only when the focused class is present (keyboard navigation) */ .network-option.focused { background-color: var(--primer-color-gray-100); } .network-option:focus-visible { outline: 2px solid var(--primer-color-focus); outline-offset: -2px; } .network-option-icon { width: var(--primer-size-medium); height: var(--primer-size-small); margin-right: var(--primer-space-small); object-fit: contain; } .network-name { font-size: var(--primer-typography-body-medium-size); font-family: var(--primer-typography-body-medium-font); line-height: var(--primer-typography-body-medium-line-height); letter-spacing: var(--primer-typography-body-medium-letter-spacing); white-space: nowrap; color: var(--primer-color-text-primary); flex: 1; } .checkmark { margin-left: var(--primer-space-small); color: var(--primer-color-brand); width: var(--primer-size-small); height: var(--primer-size-small); } `;var pe=class extends v{constructor(){super(...arguments);this.cardNetworks=null;this.headlessUtils=null;this.selectedCardNetwork=null;this.isDropdownOpen=!1;this.focusedNetworkIndex=0;this.isKeyboardNavigation=!1;this.buttonRef=Bt();this.dropdownRef=Bt();this.networkOptionRefs=[];this.toggleDropdown=e=>{this.isKeyboardNavigation=!1,e.stopPropagation(),this.getSelectableNetworks().length>1&&(this.isDropdownOpen=!this.isDropdownOpen,this.isDropdownOpen&&(this.focusedNetworkIndex=this.getSelectedNetworkIndex()))};this.handleClickOutside=e=>{this.isDropdownOpen&&(this.contains(e.target)||(this.isDropdownOpen=!1,this.isKeyboardNavigation=!1))};this.handleMouseMove=()=>{this.isKeyboardNavigation&&(this.isKeyboardNavigation=!1)};this.handleKeyDown=e=>{if(!(!(this.getSelectableNetworks().length>1)||!(this.contains(e.target)||this===e.target||this.isDropdownOpen&&e.target===document.body)))switch(this.isKeyboardNavigation=!0,e.key){case"ArrowDown":e.preventDefault(),this.isDropdownOpen?(this.focusedNetworkIndex=(this.focusedNetworkIndex+1)%this.getSelectableNetworks().length,this.focusNetworkOption()):(this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"ArrowUp":e.preventDefault(),this.isDropdownOpen?(this.focusedNetworkIndex=(this.focusedNetworkIndex-1+this.getSelectableNetworks().length)%this.getSelectableNetworks().length,this.focusNetworkOption()):(this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"Enter":case" ":this.isDropdownOpen&&this.focusedNetworkIndex>=0?(e.preventDefault(),this.selectNetwork(e,this.getSelectableNetworks()[this.focusedNetworkIndex])):!this.isDropdownOpen&&this.buttonRef.value===document.activeElement&&(e.preventDefault(),this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"Escape":this.isDropdownOpen&&(e.preventDefault(),this.isDropdownOpen=!1,this.buttonRef.value?.focus());break;case"Tab":this.isDropdownOpen&&(this.isDropdownOpen=!1);break}};this.handleDocumentKeyDown=e=>{this.isDropdownOpen&&this.handleKeyDown(e)}}getNetworkIconUrl(e){return this.headlessUtils?.getCardNetworkAsset(e.network)?.cardUrl}getSelectableNetworks(){return this.cardNetworks?.selectableCardNetworks||[]}getDetectedNetwork(){return this.selectedCardNetwork??(this.cardNetworks?.detectedCardNetwork||null)}getSelectedNetworkIndex(){let e=this.getDetectedNetwork();if(!e)return 0;let a=this.getSelectableNetworks().findIndex(i=>i.network===e.network);return a>=0?a:0}selectNetwork(e,a){e.stopPropagation(),this.selectedCardNetwork=a,this.isDropdownOpen=!1,this.buttonRef.value?.focus(),this.cardNetworks&&this.dispatchEvent(new CustomEvent("network-selected",{detail:{network:a.network},bubbles:!0,composed:!0}))}focusNetworkOption(){requestAnimationFrame(()=>{this.networkOptionRefs[this.focusedNetworkIndex]&&this.networkOptionRefs[this.focusedNetworkIndex].focus()})}setNetworkOptionRef(e,a){this.networkOptionRefs[a]=e}connectedCallback(){super.connectedCallback(),setTimeout(()=>{document.addEventListener("click",this.handleClickOutside),document.addEventListener("mousemove",this.handleMouseMove),this.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keydown",this.handleDocumentKeyDown)},0)}disconnectedCallback(){document.removeEventListener("click",this.handleClickOutside),document.removeEventListener("keydown",this.handleDocumentKeyDown),document.removeEventListener("mousemove",this.handleMouseMove),this.removeEventListener("keydown",this.handleKeyDown),super.disconnectedCallback()}render(){if(this.cardNetworks?.isLoading)return p`<primer-spinner size="small" compact></primer-spinner>`;let e=this.getSelectableNetworks();if(!this.getDetectedNetwork()&&e.length===0)return p`<primer-icon name="payment-card" size="sm"></primer-icon>`;let a=this.getDetectedNetwork()||(e.length>0?e[0]:null);if(!a)return p`<primer-icon name="payment-card" size="sm"></primer-icon>`;let i=e.length>1;return p`<button ${bt(this.buttonRef)} class="network-selector" @click=${this.toggleDropdown} @keydown=${n=>{(n.key===" "||n.key==="Enter")&&i&&(n.preventDefault(),this.isDropdownOpen=!this.isDropdownOpen,this.isDropdownOpen&&(this.focusedNetworkIndex=this.getSelectedNetworkIndex()))}} aria-label=${i?`Selected card network: ${a.displayName}. Click to change.`:`Card network: ${a.displayName}`} aria-expanded=${i?this.isDropdownOpen:g} aria-haspopup=${i?"true":g} aria-controls=${i?"network-dropdown":g} ><img class="network-icon" src=${this.getNetworkIconUrl(a)} alt=${a.displayName} />${L(i,()=>p`<primer-icon class="caret ${this.isDropdownOpen?"open":""}" size="sm" name="chevron-down" ></primer-icon>`,()=>g)}</button>${L(this.isDropdownOpen,()=>p`<div ${bt(this.dropdownRef)} id="network-dropdown" class="dropdown open" role="listbox" aria-label="Select card network" >${e.map((n,o)=>p`<div ${bt(s=>this.setNetworkOptionRef(s,o))} class="network-option ${this.isKeyboardNavigation&&o===this.focusedNetworkIndex?"focused":""}" @click=${s=>this.selectNetwork(s,n)} @keydown=${s=>{(s.key==="Enter"||s.key===" ")&&this.selectNetwork(s,n)}} role="option" aria-selected=${n.network===a.network} tabindex="${o===this.focusedNetworkIndex?"0":"-1"}" ><img class="network-option-icon" src=${this.getNetworkIconUrl(n)} alt=${n.displayName} /><span class="network-name">${n.displayName}</span>${L(n.network===a.network,()=>p`<primer-icon class="checkmark" name="checkmark" size="sm" ></primer-icon>`,()=>g)}</div>`)}</div>`,()=>g)} `}};pe.styles=[k,Kl],d([M({context:Va,subscribe:!0})],pe.prototype,"cardNetworks",2),d([M({context:Y,subscribe:!0})],pe.prototype,"headlessUtils",2),d([P()],pe.prototype,"selectedCardNetwork",2),d([P()],pe.prototype,"isDropdownOpen",2),d([P()],pe.prototype,"focusedNetworkIndex",2),d([P()],pe.prototype,"isKeyboardNavigation",2),pe=d([S("primer-card-network-selector")],pe);var Vl=f` :host { display: block; margin-top: var(--primer-space-medium); margin-bottom: var(--primer-space-medium); } .other-payment-methods-container { width: 100%; } .other-payment-methods-content { padding: var(--primer-space-medium) 0; } .primer-loader { display: flex; justify-content: center; align-items: center; } /* Collapsable animation for slotted toggle button */ .collapsable-wrapper { display: grid; grid-template-rows: 0fr; transition: grid-template-rows var(--primer-animation-duration) var(--primer-animation-easing); overflow: hidden; } .collapsable-wrapper.expanded { grid-template-rows: 1fr; } .collapsable-content { min-height: 0; } `;var _e=class extends v{constructor(){super(...arguments);this.vaultManager=null;this.contextEventsController=null;this.hasSlottedToggle=!1;this.isExpanded=!1;this._isHandlingContextEvent=!1;this._contextToggleListener=null;this.handleToggleSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasSlottedToggle=i.length>0};this.handleSlotButtonClick=e=>{let i=e.target.closest("button, primer-button");if(!i)return;let n=i;this.isToggleButton(n)&&(e.preventDefault(),this.toggleAccordion())};this.handleDirectToggle=e=>{let a=e.detail?.action;a==="expand"?this.expand():a==="collapse"?this.collapse():this.toggleAccordion()};this.handleContextToggle=e=>{if(!this._isHandlingContextEvent){this._isHandlingContextEvent=!0;try{if(e.target!==this){e.stopPropagation();let a=e.detail?.action;a==="expand"?this.expand():a==="collapse"?this.collapse():this.toggleAccordion()}}finally{this._isHandlingContextEvent=!1}}}}isToggleButton(e){let a=e.tagName.toLowerCase(),i=a==="button",n=a==="primer-button";return i&&(e.getAttribute("type")==="button"||e.hasAttribute("data-toggle"))||n&&e.hasAttribute("data-toggle")}toggleAccordion(){this.hasSlottedToggle?(this.isExpanded=!this.isExpanded,this.dispatchExpandedEvent(this.isExpanded)):this.collapsableElement&&(this.collapsableElement.isExpanded?this.collapsableElement.collapse():this.collapsableElement.expand())}dispatchExpandedEvent(e){this.dispatchEvent(new CustomEvent("show-other-payments-toggled",{bubbles:!0,composed:!0,detail:{expanded:e}}))}expand(){this.hasSlottedToggle?this.isExpanded||(this.isExpanded=!0,this.dispatchExpandedEvent(!0)):this.collapsableElement?.expand()}collapse(){this.hasSlottedToggle?this.isExpanded&&(this.isExpanded=!1,this.dispatchExpandedEvent(!1)):this.collapsableElement?.collapse()}setupContextEventListeners(){this.contextEventsController?.host&&this._contextToggleListener&&this.contextEventsController.host.addEventListener("primer:show-other-payments-toggle",this._contextToggleListener)}cleanupContextEventListeners(){this.contextEventsController?.host&&this._contextToggleListener&&this.contextEventsController.host.removeEventListener("primer:show-other-payments-toggle",this._contextToggleListener)}connectedCallback(){super.connectedCallback(),this.isExpanded=this.vaultManager?.vaultedPaymentMethods.length===0,this.addEventListener("click",this.handleSlotButtonClick),this.addEventListener("primer:show-other-payments-toggle",this.handleDirectToggle),this._contextToggleListener=e=>{this.handleContextToggle(e)},this.setupContextEventListeners()}disconnectedCallback(){this.removeEventListener("click",this.handleSlotButtonClick),this.removeEventListener("primer:show-other-payments-toggle",this.handleDirectToggle),this.cleanupContextEventListeners(),super.disconnectedCallback()}render(){if(this.vaultManager?.isLoading)return g;let e=this.vaultManager?.showEmptyState||this.vaultManager?.vaultedPaymentMethods.length;return!this.vaultManager||!this.vaultManager.enabled||!e?p`<slot name="other-payments"></slot>`:p`<div class="other-payment-methods-container"><slot name="show-other-payments-toggle-button" @slotchange=${this.handleToggleSlotChange} ></slot>${L(!this.hasSlottedToggle,()=>p`<primer-collapsable buttonVariant="secondary" .expanded="${this.vaultManager?.vaultedPaymentMethods.length===0}" .header="${b("navigateToPaymentMethods",{id:"navigateToPaymentMethods"})}" ><div class="other-payment-methods-content"><slot name="other-payments"></slot></div></primer-collapsable>`,()=>p`<div class="collapsable-wrapper ${this.isExpanded?"expanded":""}" role="region" aria-labelledby="custom-toggle-button" ><div class="collapsable-content"><div class="other-payment-methods-content"><slot name="other-payments"></slot></div></div></div>`)}</div>`}};_e.styles=[Vl],d([M({context:ge,subscribe:!0}),u({type:Object,attribute:!1})],_e.prototype,"vaultManager",2),d([M({context:Ge,subscribe:!0}),u({attribute:!1})],_e.prototype,"contextEventsController",2),d([Ue("primer-collapsable")],_e.prototype,"collapsableElement",2),d([P()],_e.prototype,"hasSlottedToggle",2),d([P()],_e.prototype,"isExpanded",2),_e=d([S("primer-show-other-payments")],_e);var qt=class extends v{render(){return p`<primer-checkout-state type="complete"></primer-checkout-state>`}};qt=d([S("primer-checkout-complete")],qt);var Dt=class extends v{constructor(){super(...arguments);this.sdkState=null}render(){return p`<primer-checkout-state type="failure" description=${this.sdkState?.primerJsError?.message||""} ></primer-checkout-state>`}};d([M({context:j,subscribe:!0}),u()],Dt.prototype,"sdkState",2),Dt=d([S("primer-checkout-error")],Dt);var Ul=f` :host { display: block; width: 100%; } `;var ct=class extends v{constructor(){super(...arguments);this.showProcessingErrors=!0}get shouldShowError(){return!this.sdkState||this.sdkState.isProcessing?!1:!!(this.sdkState.paymentFailure&&this.showProcessingErrors)}render(){return this.sdkState?p`<primer-error-message message="${b(this.sdkState.paymentFailure?.message??"",{id:"tokenizationError"})}" ?visible="${this.shouldShowError}" ></primer-error-message>`:g}};ct.styles=[Ul],d([M({context:j,subscribe:!0}),P()],ct.prototype,"sdkState",2),d([u({type:Boolean,attribute:"show-processing-errors"})],ct.prototype,"showProcessingErrors",2),ct=d([S("primer-error-message-container")],ct);var Fl=f` :host { display: contents; } .primer-main-list { display: flex; flex-direction: column; gap: var(--primer-space-small); } .primer-is-processing { opacity: 0.5; pointer-events: none; } primer-vault-manager { margin-bottom: var(--primer-space-xlarge); } `;var Qe=class extends v{constructor(){super(...arguments);this.hasAssignedContent=!1;this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.paymentMethods=null;this.sdkState=null;this.clientOptions=null}render(){return this.sdkState?.isSuccessful?p`<slot name="checkout-complete"><primer-checkout-complete></primer-checkout-complete></slot>`:p`<slot name="payments" @slotchange=${this.onSlotChange}></slot>${L(this.hasAssignedContent,()=>g,()=>p`<div class=${ie({"primer-is-processing":!!this.sdkState?.isProcessing})} ><primer-vault-manager></primer-vault-manager><primer-show-other-payments><div slot="other-payments" class="primer-main-list">${this.paymentMethods?.toArray().map(e=>p`<primer-payment-method type=${e.type} ?disabled=${this.clientOptions?.disabledPayments===!0} ></primer-payment-method>`)}</div></primer-show-other-payments><primer-error-message-container></primer-error-message-container></div>`)} `}};Qe.styles=[k,Fl],d([M({context:ht,subscribe:!0}),u()],Qe.prototype,"paymentMethods",2),d([M({context:j,subscribe:!0}),u()],Qe.prototype,"sdkState",2),d([M({context:he,subscribe:!0}),u()],Qe.prototype,"clientOptions",2),Qe=d([S("primer-main")],Qe);function zw(){Wo(),Jo()}export{Te as AchPayment,We as ApplePay,oe as BillingAddress,be as Blik,fe as Button,te as CardForm,st as CardFormCVV,pe as CardFormCardNetworkSelector,ot as CardFormCardNumber,rt as CardFormError,lt as CardFormExpiry,dt as CardFormName,Z as CardFormSubmit,Se as Collapsable,Be as Dialog,Re as DynamicPayment,ze as ErrorMessage,ct as ErrorMessageContainer,je as GooglePay,Qa as InitializedPayments,Xa as InitializedVaultedPayments,F as Input,at as InputLabel,Ye as InputWrapper,Je as PayPal,De as PaymentMethod,Le as PaymentMethodContainer,qe as PaymentMethodContentComponent,vt as Portal,ce as PortalDialog,qt as PrimerCheckoutComplete,Ee as PrimerCheckoutComponent,Dt as PrimerCheckoutFailure,it as PrimerCheckoutState,$e as PrimerIcon,ne as PrimerKlarna,Qe as PrimerMain,xe as RedirectPayment,ve as Select,_e as ShowOtherPayments,He as Spinner,J as VaultCvvInput,Pe as VaultDeleteConfirmation,nt as VaultEmptyState,Ze as VaultErrorMessage,W as VaultManager,Oe as VaultManagerHeader,Ce as VaultPaymentMethodItem,ee as VaultPaymentSubmit,Mu as injectDarkTheme,Au as injectLightTheme,Wo as injectLoaderStyles,Jo as injectThemeStyles,zw as loadPrimer};
210
+ `,t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}function Rl(r,t){return r.active!==t.active||r.dirty!==t.dirty||r.error!==t.error||r.errorCode!==t.errorCode||r.submitted!==t.submitted||r.touched!==t.touched||r.valid!==t.valid}var _r=class{constructor(t,e){this._meta={active:!1,dirty:!1,error:null,errorCode:null,submitted:!1,touched:!1,valid:!1};this._hostedInput=null;this._standardInput=null;this.host=t,this.config=e,this.host.addController(this),this.setupTask=new D(this.host,{args:()=>[this.getHostedInput()],task:this.setupHostedInput.bind(this)}),this.host.addEventListener("wrapper-click",()=>{this.focusInput()})}focusInput(){this._hostedInput?this._hostedInput.focus():this._standardInput&&this._standardInput.focus()}notifyUserInteraction(){let t=this.host.cardFormContext;t?.onUserInteraction&&t.onUserInteraction()}getHostedInput(){let{type:t}=this.config,e=this.host.cardFormContext;return e?{cardNumber:e.cardNumberInput,cvv:e.cvvInput,expire:e.expiryInput,cardholderName:e.cardholderNameInput??"cardholderName"}[t]:void 0}async setupHostedInput([t]){if(!t)return _;await this.host.updateComplete;let e=this.getTargetContainer();return e?t==="cardholderName"?this.setupStandardInput(e):this.setupHostedIframeInput(t,e):_}getTargetContainer(){return this.host.renderRoot.querySelector(this.config.containerSelector)}setupStandardInput(t){let e=document.createElement("input");return e.type="text",e.placeholder=this.host.placeholder,Ll(e,this.host),(this.host.ariaLabel||this.host.label)&&e.setAttribute("aria-label",this.host.ariaLabel??this.host.label),this.setupInputEventListeners(e),t.innerHTML="",t.appendChild(e),this._standardInput=e,!0}setupInputEventListeners(t){t.addEventListener("input",e=>{let a=e.target,n=!!a.value.trim();this.notifyUserInteraction(),this._meta={...this._meta,dirty:n},this.config.onInput?.(a.value),this.host.requestUpdate()}),t.addEventListener("focus",()=>{this.notifyUserInteraction(),this._meta.active=!0,this.host.requestUpdate()}),t.addEventListener("blur",()=>{this._meta.active=!1,this._meta.touched=!1,this.host.requestUpdate()}),t.addEventListener("keydown",e=>{if(e.key==="Enter"){e.preventDefault();let a=this.host.closest("form");a&&a.requestSubmit()}})}async setupHostedIframeInput(t,e){await new Promise(n=>requestAnimationFrame(()=>n())),this._hostedInput=t;let a=xr(this.host.computedStyles),i=a?{style:{input:{base:a}}}:void 0;return t.addEventListener("focus",()=>{this.notifyUserInteraction(),this._meta.active=!0,this.host.requestUpdate()}),t.addEventListener("blur",()=>{this._meta.active=!1,this.host.requestUpdate()}),t.addEventListener("change",n=>{let o=n;this.notifyUserInteraction(),Rl(this._meta,o)&&(this._meta={...this._meta,...o},this.host.requestUpdate())}),t.addEventListener("enter",()=>{let n=this.host.closest("form");n&&n.requestSubmit()}),await t.render(e,{placeholder:this.host.placeholder,ariaLabel:this.host.ariaLabel,...i}),!0}get meta(){return this._meta}updateMetaFromValidation(t){this._meta={...this._meta,valid:!!t.valid,error:t.error||null,errorCode:t.errorCode||null},this.host.requestUpdate()}setSubmitted(t){this._meta={...this._meta,submitted:t,...t&&{touched:!0}},this.host.requestUpdate()}hostConnected(){this.registerWithContext()}hostDisconnected(){this.unregisterFromContext(),this._hostedInput=null,this._standardInput=null}registerWithContext(){let t=this.host.cardFormContext;t?.registerInputController&&t.registerInputController(this.config.type,this)}unregisterFromContext(){let t=this.host.cardFormContext;t?.unregisterInputController&&t.unregisterInputController(this.config.type)}};var xl=f` :host { display: contents; } form { display: flex; flex-direction: column; gap: var(--primer-space-medium); width: 100%; } .card-form { display: flex; flex-direction: column; gap: var(--primer-space-medium); margin-bottom: var(--primer-space-medium); } .card-form-row { display: flex; gap: var(--primer-space-small); } `;var _l={cardholderName:"cardholderName",cardNumber:"cardNumber",cardExpiryDate:"expire",expiryDate:"expire",cardSecurityCode:"cvv",cvv:"cvv"},te=class extends v{constructor(){super(...arguments);this.hideLabels=!1;this.disabled=!1;this.hasAssignedContent=!1;this.selectedCardNetwork=null;this.formErrorMessage=null;this.paymentMethodSelectionSent=!1;this.paymentManagers=new Map;this.clientOptions=null;this.headlessUtils=null;this.analyticsUtils=null;this.contextEventsController=null;this.cardFormProvider=new $(this,{context:Zt,initialValue:null});this.eventsController=new Ft(this);this._contextCardSubmitListener=null;this._isHandlingContextEvent=!1;this.inputControllers=new Map;this.setupCardFormTask=new D(this,{task:([e])=>{if(!e?.manager)return _;let{manager:a}=e,i=a.createHostedInputs(),{cardNumberInput:n,expiryInput:o,cvvInput:s}=i;return this.cardFormProvider.setValue({cardholderNameInput:i.cardholderNameInput,cardNumberInput:n,expiryInput:o,cvvInput:s,setCardholderName:l=>{a.setCardholderName(l),this.shouldRequireCardholderName&&a.validate?.().then(c=>{let y=c?.validationErrors?.find(A=>A.name===_l.cardholderName),h=this.inputControllers.get("cardholderName");h&&h.updateMetaFromValidation({valid:!1,error:y?.message||y?.error||null,errorCode:y?.message||y?.error||null})})},setCardNetwork:l=>{this.selectedCardNetwork=l},validate:()=>a.validate(),submit:l=>a.submit(l),hideLabels:this.hideLabels,disabled:this.disabled,setSubmissionState:l=>{this.inputControllers.forEach(c=>{c.setSubmitted(l)})},propagateValidationErrors:l=>{l&&l.forEach(c=>{let m=c.field||c.name,y=c.message||c.error,h=_l[m];if(h){let A=this.inputControllers.get(h);if(A){let C={valid:!1,error:y,errorCode:y};A.updateMetaFromValidation(C)}}})},registerInputController:(l,c)=>{this.inputControllers.set(l,c)},unregisterInputController:l=>{this.inputControllers.delete(l)},onUserInteraction:()=>{this.sendPaymentMethodSelectionEvent(),this.checkAndSendPaymentDetailsEnteredEvent()}}),!0},args:()=>[this.paymentManagers.get("PAYMENT_CARD")]});this.paymentDetailsEnteredSent=!1;this.handleSlotButtonClick=e=>{let i=e.target.closest("button, primer-button");if(!i)return;let n=i;this.isSubmitButton(n)&&(e.preventDefault(),this.submitCardPayment())};this.handleDirectSubmit=e=>{e.stopPropagation(),this.submitCardPayment()};this.handleContextCardSubmit=e=>{if(!this._isHandlingContextEvent){this._isHandlingContextEvent=!0;try{e.target!==this&&(e.stopPropagation(),this.submitCardPayment())}finally{this._isHandlingContextEvent=!1}}};this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0};this.handleFormSubmit=e=>{e.preventDefault(),e.stopPropagation(),this.submitCardPayment()}}updated(e){if(super.updated(e),(e.has("hideLabels")||e.has("disabled"))&&this.cardFormProvider.value&&this.cardFormProvider.setValue({...this.cardFormProvider.value,hideLabels:this.hideLabels,disabled:this.disabled}),e.has("contextEventsController")){let a=e.get("contextEventsController");a?.host&&this._contextCardSubmitListener&&a.host.removeEventListener("primer:card-submit",this._contextCardSubmitListener),this.setupContextEventListeners()}}get shouldShowCardholderName(){let e=this.clientOptions?.card?.cardholderName;return typeof e?.visible=="boolean"?e.visible:!0}get shouldRequireCardholderName(){if(!this.shouldShowCardholderName)return!1;let e=this.clientOptions?.card?.cardholderName;return typeof e?.required=="boolean"?e.required:!0}sendPaymentMethodSelectionEvent(){this.paymentMethodSelectionSent||(this.paymentMethodSelectionSent=!0,Q({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYMENT_CARD"}))}checkAndSendPaymentDetailsEnteredEvent(){if(this.paymentDetailsEnteredSent)return;let e=this.inputControllers.get("cardNumber"),a=this.inputControllers.get("expire"),i=this.inputControllers.get("cvv"),n=e?.meta?.dirty===!0,o=a?.meta?.dirty===!0,s=i?.meta?.dirty===!0,l=!0;this.shouldRequireCardholderName&&(l=this.inputControllers.get("cardholderName")?.meta?.dirty===!0),n&&o&&s&&l&&(this.sendPaymentDetailsEnteredEvent(),this.paymentDetailsEnteredSent=!0)}sendPaymentDetailsEnteredEvent(){Q({eventName:"PAYMENT_DETAILS_ENTERED",paymentMethod:"PAYMENT_CARD"})}connectedCallback(){super.connectedCallback(),this.addEventListener("click",this.handleSlotButtonClick),this.addEventListener("primer:card-submit",this.handleDirectSubmit),this._contextCardSubmitListener=e=>{this.handleContextCardSubmit(e)},this.setupContextEventListeners()}disconnectedCallback(){this.removeEventListener("click",this.handleSlotButtonClick),this.removeEventListener("primer:card-submit",this.handleDirectSubmit),this.cleanupContextEventListeners(),super.disconnectedCallback()}setupContextEventListeners(){this.contextEventsController?.host&&this._contextCardSubmitListener&&this.contextEventsController.host.addEventListener("primer:card-submit",this._contextCardSubmitListener)}cleanupContextEventListeners(){this.contextEventsController?.host&&this._contextCardSubmitListener&&this.contextEventsController.host.removeEventListener("primer:card-submit",this._contextCardSubmitListener)}isSubmitButton(e){let a=e.tagName.toLowerCase(),i=a==="button",n=a==="primer-button";return i&&(e.getAttribute("type")==="submit"||e.hasAttribute("data-submit"))||n&&(e.getAttribute("type")==="submit"||e.hasAttribute("data-submit"))}async submitCardPayment(){let e=this.cardFormProvider.value;if(!e||this.disabled)return;this.formErrorMessage=null,e.setSubmissionState?.(!0);let a=this.querySelector("primer-billing-address")||this.renderRoot.querySelector("primer-billing-address"),i=!0;a&&(i=await a.validateForSubmission());let n=await e.validate?.();if(n?.valid&&i){if(a&&!await a.submitToSDK()){let c=b("tokenizationError",{id:"tokenizationError"});this.formErrorMessage=c,this.eventsController.dispatchFormSubmitErrors([{field:"billingAddress",name:"billingAddress",error:"BILLING_ADDRESS_SUBMISSION_FAILED",message:c}]);return}let o=this.selectedCardNetwork?{cardNetwork:this.selectedCardNetwork}:void 0;await e.submit?.(o);let s={success:!0};this.eventsController.dispatchFormSubmitSuccess(s)}else{let o=n?.validationErrors;e.propagateValidationErrors?.(o||[]),this.cardFormProvider.setValue({...e,errors:o}),this.eventsController.dispatchFormSubmitErrors(o)}}render(){return this.setupCardFormTask.status===yt.ERROR||this.setupCardFormTask.status===yt.INITIAL?g:p`<form @submit=${this.handleFormSubmit}><slot name="card-form-content" @slotchange=${this.onSlotChange}></slot>${this.setupCardFormTask.render({complete:()=>L(this.hasAssignedContent,()=>g,()=>p`<div class="card-form"><primer-input-card-number></primer-input-card-number><div class="card-form-row"><primer-input-card-expiry></primer-input-card-expiry><primer-input-cvv></primer-input-cvv></div>${L(this.shouldShowCardholderName,()=>p`<primer-input-card-holder-name></primer-input-card-holder-name>`,()=>g)}<primer-billing-address></primer-billing-address></div><primer-card-form-submit></primer-card-form-submit><primer-error-message message="${this.formErrorMessage||""}" ?visible="${!!this.formErrorMessage}" ></primer-error-message>`)})}</form>`}};te.styles=[k,xl],d([u({type:Boolean,attribute:"hide-labels",reflect:!0})],te.prototype,"hideLabels",2),d([u({type:Boolean,attribute:"disabled"})],te.prototype,"disabled",2),d([P()],te.prototype,"hasAssignedContent",2),d([P()],te.prototype,"selectedCardNetwork",2),d([P()],te.prototype,"formErrorMessage",2),d([M({context:z,subscribe:!0}),u({type:Object})],te.prototype,"paymentManagers",2),d([M({context:he}),u({attribute:!1})],te.prototype,"clientOptions",2),d([M({context:Y,subscribe:!0}),u({attribute:!1})],te.prototype,"headlessUtils",2),d([M({context:mt,subscribe:!0}),u({attribute:!1})],te.prototype,"analyticsUtils",2),d([M({context:Ge,subscribe:!0}),u({attribute:!1})],te.prototype,"contextEventsController",2),te=d([S("primer-card-form"),B()],te);var ue=class extends v{constructor(){super();this._cardFormContext=null;this.computedStyles=null;this._userAssignedProps=new Set;this._internalLabel="";this._internalPlaceholder="";this._internalAriaLabel="";this.handleWrapperClick=()=>{this.hostedInputController.focusInput()};this.hostedInputController={}}get cardFormContext(){return this._cardFormContext}set cardFormContext(e){let a=this._cardFormContext;this._cardFormContext=e,!a&&e&&this.updateComplete.then(()=>{this.hostedInputController?.registerWithContext?.()}),this.requestUpdate("cardFormContext",a)}getTranslatedValue(e){return e?typeof e=="string"?e:b(e.id,{id:e.id}):""}get label(){return this._userAssignedProps.has("label")?this._internalLabel:this.getTranslatedValue(this.config.translations.label)}set label(e){let a=this.label;e!==""?(this._userAssignedProps.add("label"),this._internalLabel=e):(this._userAssignedProps.delete("label"),this._internalLabel=""),this.requestUpdate("label",a)}get placeholder(){return this._userAssignedProps.has("placeholder")?this._internalPlaceholder:this.getTranslatedValue(this.config.translations.placeholder)}set placeholder(e){let a=this.placeholder;this._userAssignedProps.add("placeholder"),this._internalPlaceholder=e,this.requestUpdate("placeholder",a)}get ariaLabel(){return this._userAssignedProps.has("ariaLabel")?this._internalAriaLabel:this.getTranslatedValue(this.config.translations.ariaLabel)||this.getTranslatedValue(this.config.translations.label)}set ariaLabel(e){let a=this.ariaLabel;e!==""?(this._userAssignedProps.add("ariaLabel"),this._internalAriaLabel=e):(this._userAssignedProps.delete("ariaLabel"),this._internalAriaLabel=""),this.requestUpdate("ariaLabel",a)}childUpdated(){Object.defineProperty(this,"hostedInputController",{value:new _r(this,{type:this.config.inputType,containerSelector:this.config.containerSelector,onInput:this.config.onInput}),writable:!1,configurable:!1})}getError(){let e=this.hostedInputController.meta;return e.submitted||e.dirty&&e.touched?e.errorCode:null}renderInput(){if(this.hostedInputController.setupTask.status===yt.ERROR)return g;let e=this.getError();return p`<primer-input-wrapper .focusWithin="${this.hostedInputController.meta.active}" .hasError=${!!e} @wrapper-click="${this.handleWrapperClick}" >${L(!this.cardFormContext?.hideLabels,()=>p`<primer-input-label slot="label" >${this.label}</primer-input-label >`,()=>g)}<div slot="input" class="card-input-slot" id="${this.config.containerSelector.substring(1)}" aria-label="${this.ariaLabel}" ></div>${L(e,()=>p`<primer-input-error slot="error">${b(e,{id:e})}</primer-input-error>`,()=>g)}</primer-input-wrapper>`}};d([M({context:Zt,subscribe:!0})],ue.prototype,"cardFormContext",1),d([M({context:Yt,subscribe:!0}),u()],ue.prototype,"computedStyles",2),d([u({type:String})],ue.prototype,"label",1),d([u({type:String})],ue.prototype,"placeholder",1),d([u({type:String,attribute:"aria-label"})],ue.prototype,"ariaLabel",1);var wl=f` :host { display: contents; } .card-number-container { display: flex; align-items: center; width: 100%; position: relative; gap: var(--primer-space-small); } #cardNumber { flex: 1; display: flex; width: 100%; } .network-selector-container { display: flex; align-items: center; z-index: 2; } `;var At=f` .card-input-slot { display: flex; } `;var ot=class extends ue{constructor(){super();this.config={inputType:"cardNumber",containerSelector:"#cardNumber",errorName:"cardNumber-card",translations:{label:{id:"cardNumber",defaultMessage:"Card Number"},placeholder:"4111 1111 1111 1111",ariaLabel:{id:"cardNumber",defaultMessage:"Card Number"}}};this.handleNetworkSelected=e=>{let{network:a}=e.detail;this.cardFormContext&&this.cardFormContext.setCardNetwork(a)};this.childUpdated()}renderInput(){if(this.hostedInputController.setupTask.status===yt.ERROR)return g;let e=this.getError();return p`<primer-input-wrapper .focusWithin="${this.hostedInputController.meta.active}" .hasError=${!!e} >${L(!this.cardFormContext?.hideLabels,()=>p`<primer-input-label slot="label" >${this.label}</primer-input-label >`,()=>g)}<div slot="input" class="card-number-container" aria-label="${this.ariaLabel}" ><div id="${this.config.containerSelector.substring(1)}"></div><div class="network-selector-container"><primer-card-network-selector @network-selected=${this.handleNetworkSelected} ></primer-card-network-selector></div></div>${L(e,a=>p`<primer-input-error slot="error">${b(a,{id:a})}</primer-input-error>`,()=>g)}</primer-input-wrapper>`}render(){return this.renderInput()}};ot.styles=[k,At,wl],ot=d([S("primer-input-card-number"),B()],ot);var Bl=f` :host { display: contents; } `;var st=class extends ue{constructor(){super();this.config={inputType:"cvv",containerSelector:"#cvv",errorName:"cvv-card",translations:{label:"CVV",placeholder:"123"}};this.childUpdated()}render(){return this.renderInput()}};st.styles=[k,At,Bl],st=d([S("primer-input-cvv"),B()],st);var Dl=f` :host { display: contents; } `;var lt=class extends ue{constructor(){super();this.config={inputType:"expire",containerSelector:"#expiry",errorName:"expiryDate-card",translations:{label:{id:"cardExpiry",defaultMessage:"Expiry Date"},placeholder:{id:"cardExpiryPlaceholder",defaultMessage:"MM/YY"},ariaLabel:{id:"cardExpiry",defaultMessage:"Expiry Date"}}};this.childUpdated()}render(){return this.renderInput()}};lt.styles=[k,At,Dl],lt=d([S("primer-input-card-expiry"),B()],lt);var Ol=f` :host { display: contents; } `;var dt=class extends ue{constructor(){super();this.config={inputType:"cardholderName",containerSelector:"#cardFormName",errorName:"cardholderName",translations:{label:{id:"cardholderNameLabel",defaultMessage:"Cardholder Name"},placeholder:{id:"cardholderNamePlaceholder",defaultMessage:"Name on card"},ariaLabel:{id:"cardholderNameLabel",defaultMessage:"Cardholder Name"}},onInput:e=>this.handleInput(e)};this.childUpdated()}handleInput(e){this.cardFormContext?.setCardholderName?.(e)}render(){return this.renderInput()}};dt.styles=[k,At,Ol],dt=d([S("primer-input-card-holder-name"),B()],dt);var Gl=f` :host { display: contents; } `;var Z=class extends v{constructor(){super(...arguments);this._userAssignedProps=new Set;this._internalButtonText="";this.headlessUtils=null;this.clientOptions=null;this.sdkState=null;this.cardFormContext=null;this.analyticsUtils=null;this.contextEventsController=null;this.variant="primary";this.disabled=!1;this.handleClick=e=>{if(e.preventDefault(),this.disabled)return;Q({eventName:"PAYMENT_SUBMITTED",paymentMethod:"PAYMENT_CARD"});let a=new CustomEvent("primer:card-submit",{bubbles:!0,composed:!0,detail:{source:"primer-card-form-submit"}});this.dispatchEvent(a)}}get buttonText(){return this._userAssignedProps.has("buttonText")?this._internalButtonText:b("pay",{id:"pay"})}set buttonText(e){let a=this.buttonText;e!==""?(this._userAssignedProps.add("buttonText"),this._internalButtonText=e):(this._userAssignedProps.delete("buttonText"),this._internalButtonText=""),this.requestUpdate("buttonText",a)}get submitButtonConfig(){return this.clientOptions?.submitButton??null}get shouldShowBuiltInButton(){return this.submitButtonConfig?.useBuiltInButton??!0}render(){if(!this.shouldShowBuiltInButton)return g;let e=this.submitButtonConfig?.amountVisible?this.headlessUtils?.getUIOrderAmount():null,a=e?` ${e}`:g,i=this.disabled||this.cardFormContext?.disabled||!1;return p`<primer-button type="submit" variant=${this.variant} ?disabled=${i} @click=${this.handleClick} .loading=${!!this.sdkState?.isProcessing} data-submit >${this.buttonText}${a}</primer-button>`}};Z.styles=[k,Gl],d([u({type:String})],Z.prototype,"buttonText",1),d([M({context:Y,subscribe:!0}),u({type:Object})],Z.prototype,"headlessUtils",2),d([M({context:he,subscribe:!0}),u({type:Object})],Z.prototype,"clientOptions",2),d([M({context:j,subscribe:!0}),u()],Z.prototype,"sdkState",2),d([M({context:Zt,subscribe:!0}),u()],Z.prototype,"cardFormContext",2),d([M({context:mt,subscribe:!0}),u({attribute:!1})],Z.prototype,"analyticsUtils",2),d([M({context:Ge,subscribe:!0}),u({attribute:!1})],Z.prototype,"contextEventsController",2),d([u({type:String})],Z.prototype,"variant",2),d([u({type:Boolean})],Z.prototype,"disabled",2),Z=d([S("primer-card-form-submit"),B()],Z);var Kl=f` :host { display: flex; align-items: center; position: relative; } .network-selector { display: flex; align-items: center; cursor: pointer; background: none; padding: unset; border: none; transition: opacity var(--primer-animation-duration) var(--primer-animation-easing); outline: none; gap: var(--primer-space-xsmall); } .network-selector:hover { opacity: 0.8; } .network-selector:focus-visible { outline: 2px solid var(--primer-color-focus); border-radius: var(--primer-radius-xsmall); } .network-icon { width: var(--primer-size-large); height: var( --primer-size-medium ); /* Added explicit height to maintain aspect ratio */ object-fit: contain; } .caret { margin-left: var(--primer-space-xsmall); transition: transform var(--primer-animation-duration) var(--primer-animation-easing); color: var(--primer-color-icon-primary); } .caret.open { transform: rotate(180deg); } .dropdown { position: absolute; top: 100%; right: 0; width: max-content; min-width: calc(var(--primer-size-xxxlarge) * 3); background: var(--primer-color-gray-000); border-radius: var(--primer-radius-small); box-shadow: 0 var(--primer-space-xxsmall) var(--primer-space-large) rgba(0, 0, 0, 0.15); z-index: 10; overflow: hidden; border: 1px solid var(--primer-color-border-outlined-default); } .dropdown:not(.open) { display: none; } .dropdown.open { display: block; max-height: calc(var(--primer-size-xxxlarge) * 4); overflow-y: auto; } .network-option { display: flex; align-items: center; padding: var(--primer-space-small) var(--primer-space-medium); cursor: pointer; transition: background-color var(--primer-animation-duration) var(--primer-animation-easing); position: relative; outline: none; background-color: transparent; } /* Only apply hover effect when not in keyboard navigation mode */ .network-option:hover { background-color: var(--primer-color-gray-100); } /* Apply focused style only when the focused class is present (keyboard navigation) */ .network-option.focused { background-color: var(--primer-color-gray-100); } .network-option:focus-visible { outline: 2px solid var(--primer-color-focus); outline-offset: -2px; } .network-option-icon { width: var(--primer-size-medium); height: var(--primer-size-small); margin-right: var(--primer-space-small); object-fit: contain; } .network-name { font-size: var(--primer-typography-body-medium-size); font-family: var(--primer-typography-body-medium-font); line-height: var(--primer-typography-body-medium-line-height); letter-spacing: var(--primer-typography-body-medium-letter-spacing); white-space: nowrap; color: var(--primer-color-text-primary); flex: 1; } .checkmark { margin-left: var(--primer-space-small); color: var(--primer-color-brand); width: var(--primer-size-small); height: var(--primer-size-small); } `;var pe=class extends v{constructor(){super(...arguments);this.cardNetworks=null;this.headlessUtils=null;this.selectedCardNetwork=null;this.isDropdownOpen=!1;this.focusedNetworkIndex=0;this.isKeyboardNavigation=!1;this.buttonRef=Bt();this.dropdownRef=Bt();this.networkOptionRefs=[];this.toggleDropdown=e=>{this.isKeyboardNavigation=!1,e.stopPropagation(),this.getSelectableNetworks().length>1&&(this.isDropdownOpen=!this.isDropdownOpen,this.isDropdownOpen&&(this.focusedNetworkIndex=this.getSelectedNetworkIndex()))};this.handleClickOutside=e=>{this.isDropdownOpen&&(this.contains(e.target)||(this.isDropdownOpen=!1,this.isKeyboardNavigation=!1))};this.handleMouseMove=()=>{this.isKeyboardNavigation&&(this.isKeyboardNavigation=!1)};this.handleKeyDown=e=>{if(!(!(this.getSelectableNetworks().length>1)||!(this.contains(e.target)||this===e.target||this.isDropdownOpen&&e.target===document.body)))switch(this.isKeyboardNavigation=!0,e.key){case"ArrowDown":e.preventDefault(),this.isDropdownOpen?(this.focusedNetworkIndex=(this.focusedNetworkIndex+1)%this.getSelectableNetworks().length,this.focusNetworkOption()):(this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"ArrowUp":e.preventDefault(),this.isDropdownOpen?(this.focusedNetworkIndex=(this.focusedNetworkIndex-1+this.getSelectableNetworks().length)%this.getSelectableNetworks().length,this.focusNetworkOption()):(this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"Enter":case" ":this.isDropdownOpen&&this.focusedNetworkIndex>=0?(e.preventDefault(),this.selectNetwork(e,this.getSelectableNetworks()[this.focusedNetworkIndex])):!this.isDropdownOpen&&this.buttonRef.value===document.activeElement&&(e.preventDefault(),this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"Escape":this.isDropdownOpen&&(e.preventDefault(),this.isDropdownOpen=!1,this.buttonRef.value?.focus());break;case"Tab":this.isDropdownOpen&&(this.isDropdownOpen=!1);break}};this.handleDocumentKeyDown=e=>{this.isDropdownOpen&&this.handleKeyDown(e)}}getNetworkIconUrl(e){return this.headlessUtils?.getCardNetworkAsset(e.network)?.cardUrl}getSelectableNetworks(){return this.cardNetworks?.selectableCardNetworks||[]}getDetectedNetwork(){return this.selectedCardNetwork??(this.cardNetworks?.detectedCardNetwork||null)}getSelectedNetworkIndex(){let e=this.getDetectedNetwork();if(!e)return 0;let a=this.getSelectableNetworks().findIndex(i=>i.network===e.network);return a>=0?a:0}selectNetwork(e,a){e.stopPropagation(),this.selectedCardNetwork=a,this.isDropdownOpen=!1,this.buttonRef.value?.focus(),this.cardNetworks&&this.dispatchEvent(new CustomEvent("network-selected",{detail:{network:a.network},bubbles:!0,composed:!0}))}focusNetworkOption(){requestAnimationFrame(()=>{this.networkOptionRefs[this.focusedNetworkIndex]&&this.networkOptionRefs[this.focusedNetworkIndex].focus()})}setNetworkOptionRef(e,a){this.networkOptionRefs[a]=e}connectedCallback(){super.connectedCallback(),setTimeout(()=>{document.addEventListener("click",this.handleClickOutside),document.addEventListener("mousemove",this.handleMouseMove),this.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keydown",this.handleDocumentKeyDown)},0)}disconnectedCallback(){document.removeEventListener("click",this.handleClickOutside),document.removeEventListener("keydown",this.handleDocumentKeyDown),document.removeEventListener("mousemove",this.handleMouseMove),this.removeEventListener("keydown",this.handleKeyDown),super.disconnectedCallback()}render(){if(this.cardNetworks?.isLoading)return p`<primer-spinner size="small" compact></primer-spinner>`;let e=this.getSelectableNetworks();if(!this.getDetectedNetwork()&&e.length===0)return p`<primer-icon name="payment-card" size="sm"></primer-icon>`;let a=this.getDetectedNetwork()||(e.length>0?e[0]:null);if(!a)return p`<primer-icon name="payment-card" size="sm"></primer-icon>`;let i=e.length>1;return p`<button ${bt(this.buttonRef)} class="network-selector" @click=${this.toggleDropdown} @keydown=${n=>{(n.key===" "||n.key==="Enter")&&i&&(n.preventDefault(),this.isDropdownOpen=!this.isDropdownOpen,this.isDropdownOpen&&(this.focusedNetworkIndex=this.getSelectedNetworkIndex()))}} aria-label=${i?`Selected card network: ${a.displayName}. Click to change.`:`Card network: ${a.displayName}`} aria-expanded=${i?this.isDropdownOpen:g} aria-haspopup=${i?"true":g} aria-controls=${i?"network-dropdown":g} ><img class="network-icon" src=${this.getNetworkIconUrl(a)} alt=${a.displayName} />${L(i,()=>p`<primer-icon class="caret ${this.isDropdownOpen?"open":""}" size="sm" name="chevron-down" ></primer-icon>`,()=>g)}</button>${L(this.isDropdownOpen,()=>p`<div ${bt(this.dropdownRef)} id="network-dropdown" class="dropdown open" role="listbox" aria-label="Select card network" >${e.map((n,o)=>p`<div ${bt(s=>this.setNetworkOptionRef(s,o))} class="network-option ${this.isKeyboardNavigation&&o===this.focusedNetworkIndex?"focused":""}" @click=${s=>this.selectNetwork(s,n)} @keydown=${s=>{(s.key==="Enter"||s.key===" ")&&this.selectNetwork(s,n)}} role="option" aria-selected=${n.network===a.network} tabindex="${o===this.focusedNetworkIndex?"0":"-1"}" ><img class="network-option-icon" src=${this.getNetworkIconUrl(n)} alt=${n.displayName} /><span class="network-name">${n.displayName}</span>${L(n.network===a.network,()=>p`<primer-icon class="checkmark" name="checkmark" size="sm" ></primer-icon>`,()=>g)}</div>`)}</div>`,()=>g)} `}};pe.styles=[k,Kl],d([M({context:Va,subscribe:!0})],pe.prototype,"cardNetworks",2),d([M({context:Y,subscribe:!0})],pe.prototype,"headlessUtils",2),d([P()],pe.prototype,"selectedCardNetwork",2),d([P()],pe.prototype,"isDropdownOpen",2),d([P()],pe.prototype,"focusedNetworkIndex",2),d([P()],pe.prototype,"isKeyboardNavigation",2),pe=d([S("primer-card-network-selector")],pe);var Vl=f` :host { display: block; margin-top: var(--primer-space-medium); margin-bottom: var(--primer-space-medium); } .other-payment-methods-container { width: 100%; } .other-payment-methods-content { padding: var(--primer-space-medium) 0; } .primer-loader { display: flex; justify-content: center; align-items: center; } /* Collapsable animation for slotted toggle button */ .collapsable-wrapper { display: grid; grid-template-rows: 0fr; transition: grid-template-rows var(--primer-animation-duration) var(--primer-animation-easing); overflow: hidden; } .collapsable-wrapper.expanded { grid-template-rows: 1fr; } .collapsable-content { min-height: 0; } `;var _e=class extends v{constructor(){super(...arguments);this.vaultManager=null;this.contextEventsController=null;this.hasSlottedToggle=!1;this.isExpanded=!1;this._isHandlingContextEvent=!1;this._contextToggleListener=null;this.handleToggleSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasSlottedToggle=i.length>0};this.handleSlotButtonClick=e=>{let i=e.target.closest("button, primer-button");if(!i)return;let n=i;this.isToggleButton(n)&&(e.preventDefault(),this.toggleAccordion())};this.handleDirectToggle=e=>{let a=e.detail?.action;a==="expand"?this.expand():a==="collapse"?this.collapse():this.toggleAccordion()};this.handleContextToggle=e=>{if(!this._isHandlingContextEvent){this._isHandlingContextEvent=!0;try{if(e.target!==this){e.stopPropagation();let a=e.detail?.action;a==="expand"?this.expand():a==="collapse"?this.collapse():this.toggleAccordion()}}finally{this._isHandlingContextEvent=!1}}}}isToggleButton(e){let a=this.shadowRoot?.querySelector('slot[name="show-other-payments-toggle-button"]');return a?a.assignedElements({flatten:!0}).some(n=>n===e||n.contains(e)):!1}toggleAccordion(){this.hasSlottedToggle?(this.isExpanded=!this.isExpanded,this.dispatchExpandedEvent(this.isExpanded)):this.collapsableElement&&(this.collapsableElement.isExpanded?this.collapsableElement.collapse():this.collapsableElement.expand())}dispatchExpandedEvent(e){this.dispatchEvent(new CustomEvent("primer:show-other-payments-toggled",{bubbles:!0,composed:!0,detail:{expanded:e}}))}expand(){this.hasSlottedToggle?this.isExpanded||(this.isExpanded=!0,this.dispatchExpandedEvent(!0)):this.collapsableElement?.expand()}collapse(){this.hasSlottedToggle?this.isExpanded&&(this.isExpanded=!1,this.dispatchExpandedEvent(!1)):this.collapsableElement?.collapse()}setupContextEventListeners(){this.contextEventsController?.host&&this._contextToggleListener&&this.contextEventsController.host.addEventListener("primer:show-other-payments-toggle",this._contextToggleListener)}cleanupContextEventListeners(){this.contextEventsController?.host&&this._contextToggleListener&&this.contextEventsController.host.removeEventListener("primer:show-other-payments-toggle",this._contextToggleListener)}connectedCallback(){super.connectedCallback(),this.isExpanded=this.vaultManager?.vaultedPaymentMethods.length===0,this.addEventListener("click",this.handleSlotButtonClick),this.addEventListener("primer:show-other-payments-toggle",this.handleDirectToggle),this._contextToggleListener=e=>{this.handleContextToggle(e)},this.setupContextEventListeners()}disconnectedCallback(){this.removeEventListener("click",this.handleSlotButtonClick),this.removeEventListener("primer:show-other-payments-toggle",this.handleDirectToggle),this.cleanupContextEventListeners(),super.disconnectedCallback()}render(){if(this.vaultManager?.isLoading)return g;let e=this.vaultManager?.showEmptyState||this.vaultManager?.vaultedPaymentMethods.length;return!this.vaultManager||!this.vaultManager.enabled||!e?p`<slot name="other-payments"></slot>`:p`<div class="other-payment-methods-container"><slot name="show-other-payments-toggle-button" @slotchange=${this.handleToggleSlotChange} ></slot>${L(!this.hasSlottedToggle,()=>p`<primer-collapsable buttonVariant="secondary" .expanded="${this.vaultManager?.vaultedPaymentMethods.length===0}" .header="${b("navigateToPaymentMethods",{id:"navigateToPaymentMethods"})}" ><div class="other-payment-methods-content"><slot name="other-payments"></slot></div></primer-collapsable>`,()=>p`<div class="collapsable-wrapper ${this.isExpanded?"expanded":""}" role="region" aria-labelledby="custom-toggle-button" ><div class="collapsable-content"><div class="other-payment-methods-content"><slot name="other-payments"></slot></div></div></div>`)}</div>`}};_e.styles=[Vl],d([M({context:ge,subscribe:!0}),u({type:Object,attribute:!1})],_e.prototype,"vaultManager",2),d([M({context:Ge,subscribe:!0}),u({attribute:!1})],_e.prototype,"contextEventsController",2),d([Ue("primer-collapsable")],_e.prototype,"collapsableElement",2),d([P()],_e.prototype,"hasSlottedToggle",2),d([P()],_e.prototype,"isExpanded",2),_e=d([S("primer-show-other-payments")],_e);var qt=class extends v{render(){return p`<primer-checkout-state type="complete"></primer-checkout-state>`}};qt=d([S("primer-checkout-complete")],qt);var Dt=class extends v{constructor(){super(...arguments);this.sdkState=null}render(){return p`<primer-checkout-state type="failure" description=${this.sdkState?.primerJsError?.message||""} ></primer-checkout-state>`}};d([M({context:j,subscribe:!0}),u()],Dt.prototype,"sdkState",2),Dt=d([S("primer-checkout-error")],Dt);var Ul=f` :host { display: block; width: 100%; } `;var ct=class extends v{constructor(){super(...arguments);this.showProcessingErrors=!0}get shouldShowError(){return!this.sdkState||this.sdkState.isProcessing?!1:!!(this.sdkState.paymentFailure&&this.showProcessingErrors)}render(){return this.sdkState?p`<primer-error-message message="${b(this.sdkState.paymentFailure?.message??"",{id:"tokenizationError"})}" ?visible="${this.shouldShowError}" ></primer-error-message>`:g}};ct.styles=[Ul],d([M({context:j,subscribe:!0}),P()],ct.prototype,"sdkState",2),d([u({type:Boolean,attribute:"show-processing-errors"})],ct.prototype,"showProcessingErrors",2),ct=d([S("primer-error-message-container")],ct);var Fl=f` :host { display: contents; } .primer-main-list { display: flex; flex-direction: column; gap: var(--primer-space-small); } .primer-is-processing { opacity: 0.5; pointer-events: none; } primer-vault-manager { margin-bottom: var(--primer-space-xlarge); } `;var Qe=class extends v{constructor(){super(...arguments);this.hasAssignedContent=!1;this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.paymentMethods=null;this.sdkState=null;this.clientOptions=null}render(){return this.sdkState?.isSuccessful?p`<slot name="checkout-complete"><primer-checkout-complete></primer-checkout-complete></slot>`:p`<slot name="payments" @slotchange=${this.onSlotChange}></slot>${L(this.hasAssignedContent,()=>g,()=>p`<div class=${ie({"primer-is-processing":!!this.sdkState?.isProcessing})} ><primer-vault-manager></primer-vault-manager><primer-show-other-payments><div slot="other-payments" class="primer-main-list">${this.paymentMethods?.toArray().map(e=>p`<primer-payment-method type=${e.type} ?disabled=${this.clientOptions?.disabledPayments===!0} ></primer-payment-method>`)}</div></primer-show-other-payments><primer-error-message-container></primer-error-message-container></div>`)} `}};Qe.styles=[k,Fl],d([M({context:ht,subscribe:!0}),u()],Qe.prototype,"paymentMethods",2),d([M({context:j,subscribe:!0}),u()],Qe.prototype,"sdkState",2),d([M({context:he,subscribe:!0}),u()],Qe.prototype,"clientOptions",2),Qe=d([S("primer-main")],Qe);function zw(){Wo(),Jo()}export{Te as AchPayment,We as ApplePay,oe as BillingAddress,be as Blik,fe as Button,te as CardForm,st as CardFormCVV,pe as CardFormCardNetworkSelector,ot as CardFormCardNumber,rt as CardFormError,lt as CardFormExpiry,dt as CardFormName,Z as CardFormSubmit,Se as Collapsable,Be as Dialog,Re as DynamicPayment,ze as ErrorMessage,ct as ErrorMessageContainer,je as GooglePay,Qa as InitializedPayments,Xa as InitializedVaultedPayments,F as Input,at as InputLabel,Ye as InputWrapper,Je as PayPal,De as PaymentMethod,Le as PaymentMethodContainer,qe as PaymentMethodContentComponent,vt as Portal,ce as PortalDialog,qt as PrimerCheckoutComplete,Ee as PrimerCheckoutComponent,Dt as PrimerCheckoutFailure,it as PrimerCheckoutState,$e as PrimerIcon,ne as PrimerKlarna,Qe as PrimerMain,xe as RedirectPayment,ve as Select,_e as ShowOtherPayments,He as Spinner,J as VaultCvvInput,Pe as VaultDeleteConfirmation,nt as VaultEmptyState,Ze as VaultErrorMessage,W as VaultManager,Oe as VaultManagerHeader,Ce as VaultPaymentMethodItem,ee as VaultPaymentSubmit,Mu as injectDarkTheme,Au as injectLightTheme,Wo as injectLoaderStyles,Jo as injectThemeStyles,zw as loadPrimer};
@@ -466,7 +466,7 @@
466
466
  },
467
467
  {
468
468
  "name": "primer-show-other-payments",
469
- "description": "Component for showing/hiding other payment methods when vault is present\nUtilizes the collapsable component for smooth transitions\nSupports custom toggle buttons via slots and external control via events\n---\n\n\n### **Events:**\n - **show-other-payments-toggled**\n\n### **Methods:**\n - **expand(): _void_** - Public API: Expand the accordion programmatically\n- **collapse(): _void_** - Public API: Collapse the accordion programmatically",
469
+ "description": "Component for showing/hiding other payment methods when vault is present\nUtilizes the collapsable component for smooth transitions\nSupports custom toggle buttons via slots and external control via events\n---\n\n\n### **Events:**\n - **primer:show-other-payments-toggled**\n\n### **Methods:**\n - **expand(): _void_** - Public API: Expand the accordion programmatically\n- **collapse(): _void_** - Public API: Collapse the accordion programmatically",
470
470
  "attributes": [],
471
471
  "references": []
472
472
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://raw.githubusercontent.com/JetBrains/web-types/master/schema/web-types.json",
3
3
  "name": "@primer-io/primer-js",
4
- "version": "0.8.1",
4
+ "version": "0.8.2",
5
5
  "description-markup": "markdown",
6
6
  "contributions": {
7
7
  "html": {
@@ -1247,11 +1247,14 @@
1247
1247
  },
1248
1248
  {
1249
1249
  "name": "primer-show-other-payments",
1250
- "description": "Component for showing/hiding other payment methods when vault is present\nUtilizes the collapsable component for smooth transitions\nSupports custom toggle buttons via slots and external control via events\n---\n\n\n### **Events:**\n - **show-other-payments-toggled**\n\n### **Methods:**\n - **expand(): _void_** - Public API: Expand the accordion programmatically\n- **collapse(): _void_** - Public API: Collapse the accordion programmatically",
1250
+ "description": "Component for showing/hiding other payment methods when vault is present\nUtilizes the collapsable component for smooth transitions\nSupports custom toggle buttons via slots and external control via events\n---\n\n\n### **Events:**\n - **primer:show-other-payments-toggled**\n\n### **Methods:**\n - **expand(): _void_** - Public API: Expand the accordion programmatically\n- **collapse(): _void_** - Public API: Collapse the accordion programmatically",
1251
1251
  "doc-url": "",
1252
1252
  "attributes": [],
1253
1253
  "events": [
1254
- { "name": "show-other-payments-toggled", "type": "CustomEvent" }
1254
+ {
1255
+ "name": "primer:show-other-payments-toggled",
1256
+ "type": "CustomEvent"
1257
+ }
1255
1258
  ],
1256
1259
  "js": {
1257
1260
  "properties": [
@@ -1267,7 +1270,10 @@
1267
1270
  }
1268
1271
  ],
1269
1272
  "events": [
1270
- { "name": "show-other-payments-toggled", "type": "CustomEvent" }
1273
+ {
1274
+ "name": "primer:show-other-payments-toggled",
1275
+ "type": "CustomEvent"
1276
+ }
1271
1277
  ]
1272
1278
  }
1273
1279
  },
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@primer-io/primer-js",
3
3
  "description": "Primer Checkout is a web component-based SDK for building secure, customizable, and PCI-compliant checkout experiences. Designed with a modular architecture, it integrates seamlessly with any JavaScript framework and supports multiple payment methods.",
4
4
  "license": "BSD-3-Clause",
5
- "version": "0.8.1",
5
+ "version": "0.8.2",
6
6
  "type": "module",
7
7
  "main": "./dist/primer-loader.js",
8
8
  "types": "./dist/primer-loader.d.ts",