@primer-io/primer-js 1.0.2 → 1.0.4
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 +12 -0
- package/dist/custom-elements.json +85 -85
- package/dist/primer-loader.js +5 -3
- package/dist/web-types.json +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @primer-io/primer-js
|
|
2
2
|
|
|
3
|
+
## 1.0.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 4285464: fix: css rule is too permissive causing a whole checkout to disappear when grammarly plugin is turned on (and potentially other plugins)
|
|
8
|
+
|
|
9
|
+
## 1.0.3
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 0c01bf1: fix full-year autocomplete
|
|
14
|
+
|
|
3
15
|
## 1.0.2
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
|
@@ -2,6 +2,35 @@
|
|
|
2
2
|
"schemaVersion": "1.0.0",
|
|
3
3
|
"readme": "",
|
|
4
4
|
"modules": [
|
|
5
|
+
{
|
|
6
|
+
"kind": "javascript-module",
|
|
7
|
+
"path": "e2e/utils.ts",
|
|
8
|
+
"declarations": [
|
|
9
|
+
{
|
|
10
|
+
"kind": "variable",
|
|
11
|
+
"name": "test",
|
|
12
|
+
"default": "chromaticTest"
|
|
13
|
+
}
|
|
14
|
+
],
|
|
15
|
+
"exports": [
|
|
16
|
+
{
|
|
17
|
+
"kind": "js",
|
|
18
|
+
"name": "expect",
|
|
19
|
+
"declaration": {
|
|
20
|
+
"name": "expect",
|
|
21
|
+
"package": "@chromatic-com/playwright"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"kind": "js",
|
|
26
|
+
"name": "test",
|
|
27
|
+
"declaration": {
|
|
28
|
+
"name": "test",
|
|
29
|
+
"module": "e2e/utils.ts"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
},
|
|
5
34
|
{
|
|
6
35
|
"kind": "javascript-module",
|
|
7
36
|
"path": "dist/primer-loader.js",
|
|
@@ -734,35 +763,6 @@
|
|
|
734
763
|
}
|
|
735
764
|
]
|
|
736
765
|
},
|
|
737
|
-
{
|
|
738
|
-
"kind": "javascript-module",
|
|
739
|
-
"path": "e2e/utils.ts",
|
|
740
|
-
"declarations": [
|
|
741
|
-
{
|
|
742
|
-
"kind": "variable",
|
|
743
|
-
"name": "test",
|
|
744
|
-
"default": "chromaticTest"
|
|
745
|
-
}
|
|
746
|
-
],
|
|
747
|
-
"exports": [
|
|
748
|
-
{
|
|
749
|
-
"kind": "js",
|
|
750
|
-
"name": "expect",
|
|
751
|
-
"declaration": {
|
|
752
|
-
"name": "expect",
|
|
753
|
-
"package": "@chromatic-com/playwright"
|
|
754
|
-
}
|
|
755
|
-
},
|
|
756
|
-
{
|
|
757
|
-
"kind": "js",
|
|
758
|
-
"name": "test",
|
|
759
|
-
"declaration": {
|
|
760
|
-
"name": "test",
|
|
761
|
-
"module": "e2e/utils.ts"
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
]
|
|
765
|
-
},
|
|
766
766
|
{
|
|
767
767
|
"kind": "javascript-module",
|
|
768
768
|
"path": "src/consts.ts",
|
|
@@ -1649,6 +1649,61 @@
|
|
|
1649
1649
|
}
|
|
1650
1650
|
]
|
|
1651
1651
|
},
|
|
1652
|
+
{
|
|
1653
|
+
"kind": "javascript-module",
|
|
1654
|
+
"path": "e2e/mocks/shared.ts",
|
|
1655
|
+
"declarations": [
|
|
1656
|
+
{
|
|
1657
|
+
"kind": "function",
|
|
1658
|
+
"name": "mockConfigurationCall",
|
|
1659
|
+
"parameters": [
|
|
1660
|
+
{
|
|
1661
|
+
"name": "page",
|
|
1662
|
+
"type": {
|
|
1663
|
+
"text": "Page"
|
|
1664
|
+
}
|
|
1665
|
+
},
|
|
1666
|
+
{
|
|
1667
|
+
"name": "config",
|
|
1668
|
+
"type": {
|
|
1669
|
+
"text": "unknown"
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
]
|
|
1673
|
+
},
|
|
1674
|
+
{
|
|
1675
|
+
"kind": "function",
|
|
1676
|
+
"name": "mockDemoUrl",
|
|
1677
|
+
"parameters": [
|
|
1678
|
+
{
|
|
1679
|
+
"name": "primerCheckoutOptions",
|
|
1680
|
+
"optional": true,
|
|
1681
|
+
"type": {
|
|
1682
|
+
"text": "PrimerCheckoutOptions"
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
]
|
|
1686
|
+
}
|
|
1687
|
+
],
|
|
1688
|
+
"exports": [
|
|
1689
|
+
{
|
|
1690
|
+
"kind": "js",
|
|
1691
|
+
"name": "mockConfigurationCall",
|
|
1692
|
+
"declaration": {
|
|
1693
|
+
"name": "mockConfigurationCall",
|
|
1694
|
+
"module": "e2e/mocks/shared.ts"
|
|
1695
|
+
}
|
|
1696
|
+
},
|
|
1697
|
+
{
|
|
1698
|
+
"kind": "js",
|
|
1699
|
+
"name": "mockDemoUrl",
|
|
1700
|
+
"declaration": {
|
|
1701
|
+
"name": "mockDemoUrl",
|
|
1702
|
+
"module": "e2e/mocks/shared.ts"
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
]
|
|
1706
|
+
},
|
|
1652
1707
|
{
|
|
1653
1708
|
"kind": "javascript-module",
|
|
1654
1709
|
"path": "dist/chunks/ar.4ZFBST5B.js",
|
|
@@ -2782,61 +2837,6 @@
|
|
|
2782
2837
|
}
|
|
2783
2838
|
]
|
|
2784
2839
|
},
|
|
2785
|
-
{
|
|
2786
|
-
"kind": "javascript-module",
|
|
2787
|
-
"path": "e2e/mocks/shared.ts",
|
|
2788
|
-
"declarations": [
|
|
2789
|
-
{
|
|
2790
|
-
"kind": "function",
|
|
2791
|
-
"name": "mockConfigurationCall",
|
|
2792
|
-
"parameters": [
|
|
2793
|
-
{
|
|
2794
|
-
"name": "page",
|
|
2795
|
-
"type": {
|
|
2796
|
-
"text": "Page"
|
|
2797
|
-
}
|
|
2798
|
-
},
|
|
2799
|
-
{
|
|
2800
|
-
"name": "config",
|
|
2801
|
-
"type": {
|
|
2802
|
-
"text": "unknown"
|
|
2803
|
-
}
|
|
2804
|
-
}
|
|
2805
|
-
]
|
|
2806
|
-
},
|
|
2807
|
-
{
|
|
2808
|
-
"kind": "function",
|
|
2809
|
-
"name": "mockDemoUrl",
|
|
2810
|
-
"parameters": [
|
|
2811
|
-
{
|
|
2812
|
-
"name": "primerCheckoutOptions",
|
|
2813
|
-
"optional": true,
|
|
2814
|
-
"type": {
|
|
2815
|
-
"text": "PrimerCheckoutOptions"
|
|
2816
|
-
}
|
|
2817
|
-
}
|
|
2818
|
-
]
|
|
2819
|
-
}
|
|
2820
|
-
],
|
|
2821
|
-
"exports": [
|
|
2822
|
-
{
|
|
2823
|
-
"kind": "js",
|
|
2824
|
-
"name": "mockConfigurationCall",
|
|
2825
|
-
"declaration": {
|
|
2826
|
-
"name": "mockConfigurationCall",
|
|
2827
|
-
"module": "e2e/mocks/shared.ts"
|
|
2828
|
-
}
|
|
2829
|
-
},
|
|
2830
|
-
{
|
|
2831
|
-
"kind": "js",
|
|
2832
|
-
"name": "mockDemoUrl",
|
|
2833
|
-
"declaration": {
|
|
2834
|
-
"name": "mockDemoUrl",
|
|
2835
|
-
"module": "e2e/mocks/shared.ts"
|
|
2836
|
-
}
|
|
2837
|
-
}
|
|
2838
|
-
]
|
|
2839
|
-
},
|
|
2840
2840
|
{
|
|
2841
2841
|
"kind": "javascript-module",
|
|
2842
2842
|
"path": "src/__tests__/setup.ts",
|
|
@@ -5629,7 +5629,7 @@
|
|
|
5629
5629
|
{
|
|
5630
5630
|
"kind": "variable",
|
|
5631
5631
|
"name": "cssLoaderStyles",
|
|
5632
|
-
"default": "` @keyframes primer-css-spinner-rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } primer-checkout:has(:not(:defined)) > * { visibility: hidden; } primer-checkout:not([js-initialized]) { display: block; position: relative; width: 100%; min-height: 64px; } primer-checkout:not([js-initialized]):not([loader-disabled])::after { content: \"\"; display: block; box-sizing: border-box; position: absolute; inset: 0; margin: auto; width: var(--primer-size-xlarge); height: var(--primer-size-xlarge); border-radius: 50%; border: 3px solid #f5f5f5; border-top-color: var(--primer-color-loader); animation: primer-css-spinner-rotate 1.2s linear infinite; z-index: 9999; } `",
|
|
5632
|
+
"default": "` @keyframes primer-css-spinner-rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } /* Hide primer-main while primer components are loading to prevent FOUC Only check for undefined primer-* elements, ignoring browser extensions */ primer-checkout:has(primer-main:not(:defined), primer-checkout-error:not(:defined)) > * { visibility: hidden; } primer-checkout:not([js-initialized]) { display: block; position: relative; width: 100%; min-height: 64px; } primer-checkout:not([js-initialized]):not([loader-disabled])::after { content: \"\"; display: block; box-sizing: border-box; position: absolute; inset: 0; margin: auto; width: var(--primer-size-xlarge); height: var(--primer-size-xlarge); border-radius: 50%; border: 3px solid #f5f5f5; border-top-color: var(--primer-color-loader); animation: primer-css-spinner-rotate 1.2s linear infinite; z-index: 9999; } `",
|
|
5633
5633
|
"description": "This module exports the CSS loader styles as a string for inline injection.\nThese styles are injected into the page before any JavaScript loads,\nensuring the loading indicator appears immediately."
|
|
5634
5634
|
}
|
|
5635
5635
|
],
|
package/dist/primer-loader.js
CHANGED
|
@@ -33,7 +33,7 @@ import{a as Wa,b as q,c as Pi,d,e as k}from"./chunks/chunk.QNO3CTH5.js";var ac=q
|
|
|
33
33
|
--apple-pay-button-width: 100%;
|
|
34
34
|
--apple-pay-button-height: ${a}px;
|
|
35
35
|
}
|
|
36
|
-
`,e.appendChild(i);let n=document.createElement("apple-pay-button"),o=this.clientOptions?.buttonStyle??this.clientOptions?.buttonOptions?.buttonStyle;o&&n.setAttribute("buttonstyle",o);let s=this.clientOptions?.buttonType??this.clientOptions?.buttonOptions?.type??"plain";s&&n.setAttribute("type",s),n.setAttribute("locale",this.context.locale),n.addEventListener("click",this.handleClick.bind(this)),document.body.appendChild(n),setTimeout(()=>{e.appendChild(n)},0)}async handleClick(){if(!this.disabled)try{this.onStartPromise=this.callbacks.onStart(),wt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:O.APPLE_PAY}),this.applePaySession=new ApplePaySession(oo,bu(this.context,this.config)),this.applePaySession.onvalidatemerchant=this.handleValidateMerchant.bind(this),this.applePaySession.onpaymentauthorized=this.handlePaymentAuthorized.bind(this),this.applePaySession.onpaymentmethodselected=this.handlePaymentMethodSelected.bind(this),this.applePaySession.onshippingcontactselected=this.handleShippingContactSelected.bind(this),this.applePaySession.onshippingmethodselected=this.handleShippingMethodSelected.bind(this),this.applePaySession.oncancel=this.handleCancel.bind(this),this.applePaySession.begin()}catch(e){C.errorWithDatadog("Error initiating Apple Pay session",{error:e})}}async handleValidateMerchant(e){if(this.applePaySession)try{let{action:a}=await this.onStartPromise;if(a==="abort")return void this.abort(new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let{data:i,error:n}=await this.context.coreApi.createApplePaySession({validationUrl:e.validationURL,paymentMethodConfigId:this.config.id,merchantDomain:this.context.clientOptions.merchantDomain??window.location.hostname});if(!this.applePaySession)return;if(n||!i)throw n??new G({message:"Failed to validate merchant",code:Q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(a){C.warn("Apple Pay merchant validation failed:",a),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(ki(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling payment method selection",{error:a}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let a=[new ApplePayError("unknown",void 0,this.context.translate(Sa.UNKNOWN_ERROR,ba.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=Ii(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw a=[new ApplePayError("billingContactInvalid","name",this.context.translate(Sa.MISSING_FIRST_OR_LAST_NAME,ba.MISSING_FIRST_OR_LAST_NAME))],new G({message:"Billing contact must include first and last name",code:xt.MISSING_PARAMETER,paymentMethod:O.APPLE_PAY,suggestion:"Ensure Apple Pay requiredBillingContactFields includes name fields"});let{error:l}=await this.context.clientSessionApi.setBillingAddress(s);l&&C.errorWithDatadog("Error setting billing address from Apple Pay",{error:l})}}let i=Ii(e.payment.shippingContact);if(i){let{error:s}=await this.context.clientSessionApi.setShippingAddress(i,e.payment.shippingContact?.phoneNumber,e.payment.shippingContact?.emailAddress);if(s)throw s}let{data:n,error:o}=await this.context.pciApi.postApplePayPaymentInstruments({paymentMethodConfigId:this.config.id,token:e.payment.token});if(o||!n)throw a=[new ApplePayError("unknown",void 0,this.context.translate(Sa.FAILED_TO_TOKENIZE,ba.FAILED_TO_TOKENIZE))],o??new Error("Failed to tokenize Apple Pay payment");this.applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS),this.callbacks.onFinish(n),this.applePaySession=null}catch(i){let n=i instanceof G||i instanceof z?i:new G({message:"Error handling payment authorization",code:F.PAYMENT_FAILED,paymentMethod:O.APPLE_PAY,error:i instanceof Error?i:new Error(String(i))});C.errorWithDatadog("Apple Pay payment authorization failed",{error:n}),this.applePaySession&&(this.applePaySession.completePayment({status:ApplePaySession.STATUS_FAILURE,errors:a}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:a,error:i}=await this.context.clientSessionApi.setShippingAddress(Ii(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!a||i)throw i??new G({message:"Failed to set shipping address",code:Q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY});this.applePaySession.completeShippingContactSelection(ki(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling shipping contact selection",{error:a}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let a=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&a){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new G({message:"Failed to select shipping method",code:Q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(ki(this.context,this.config))}catch(i){C.errorWithDatadog("Error handling shipping method selection",{error:i}),this.abort();return}}handleCancel(){this.applePaySession=null,this.context.clientSessionApi.unselectPaymentMethod(),C.info("Apple Pay payment was cancelled by the user")}abort(e){this.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onFinish(void 0,e??new Error("Apple Pay payment aborted"))}},sr=class extends gt{constructor(){super(...arguments);k(this,"blikCode","")}setBlikCode(e){this.blikCode=e}getBlikCode(){return this.blikCode}clearBlikCode(){this.blikCode=""}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new z({message:"BLIK code must be exactly 6 digits",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e={type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Uo()?"MOBILE_WEB":"WEB",browserInfo:Qi(),blikCode:this.blikCode}};try{let{error:a,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),a||!i)throw a??new z({message:"Unable to tokenize BLIK payment method",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(a){throw this.clearBlikCode(),a}}async createPayment(e){let a=await super.createPayment(e),i=a.requiredAction?.clientToken;if(!i)throw new Ge({message:"No client token provided for BLIK payment",code:no.MISSING_CLIENT_TOKEN,response:{id:a.id,data:a}});let n=Jt(i);if(!this.isValidBlikClientToken(n))throw new Ge({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:no.INVALID_CLIENT_TOKEN,response:{id:a.id,data:a}});let{promise:o,abort:s}=this.pollStatus(n.statusUrl),l=await o;if(s(),"error"in l)throw l.error;let c=l.id;if(!c){let m=await this.context.pciApi.getResumeStatus(n.statusUrl);if(m.error||!m.data?.id)throw m.error??new Error("Unable to get resume token");c=m.data.id}return await this.resumePayment(a.id,c)}pollStatus(e){let a=!0,i=1e3,n=864e5,o=Date.now();return{promise:new Promise(async s=>{for(;a;){if(Date.now()-o>=n)return void s({error:new Error("BLIK payment polling timed out after 24 hours")});let{data:l,error:c}=await this.context.pciApi.getResumeStatus(e);if(c)return void s({error:c instanceof Error?c:new Error(String(c))});if(l?.status==="COMPLETE")return void s({id:l.id});await qt(i)}}),abort:()=>{a=!1}}}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let a=e;return!(a.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in a)||typeof a.statusUrl!="string"||!a.statusUrl)}},Wo="https://sdk.primer.io/web/hosted-pages/v0.0.23",Fi=!1,Cu=`${Wo}/api-controller.html`,Mu=`${Wo}/hosted-input.html`,Eu="https://goat-assets.production.core.primer.io";function Zo(r,t,e){let a={checkoutSessionId:r,name:t};e!==void 0&&(a.defaultValue=e);try{return btoa(JSON.stringify(a))}catch{let{defaultValue:n,...o}=a;return btoa(JSON.stringify(o))}}ji("../../node_modules/card-validator/dist/index.js");var ue={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},lo="cardSecurityCodeRecapture";Object.values(ue);function Tu({networks:r,source:t},e){let a=e,i=new Set(a.map(m=>ur(m).backend)),n=r.map(m=>({...m,allowed:i.has(m.network)})).sort((m,g)=>m.allowed?a.indexOf(m.network)-a.indexOf(g.network):1),o=n.filter(m=>m.allowed),s=t==="REMOTE"&&o.length>1,[l,...c]=n;return{cardNetworkChangeEventData:{detectedCardNetworks:{items:n.map(Qa),preferred:o.length?Qa(o[0]):void 0},...s&&{selectableCardNetworks:{items:o.map(Qa),preferred:o.length?Qa(o[0]):void 0}},source:t},binDataAvailableEventData:{preferred:l,alternatives:c,status:t==="REMOTE"?"complete":"partial"}}}function Qa({network:r,displayName:t,allowed:e}){return{network:r,displayName:t,allowed:e}}function Jo(r,t){return{cardNumber:va(r,ue.cardNumber),cardSecurityCode:va(r,ue.cardSecurityCode),cardExpiryDate:va(r,ue.cardExpiryDate),cardholderName:va(r,ue.cardholderName,t?.cardholderName)}}function va(r,t,e){let a=document.createElement("iframe"),i=Zo(r,t,e);return a.src=`${Mu}#${i}`,a.setAttribute("tabindex","0"),a.setAttribute("frameBorder","0"),a.style.border="none",a.style.boxSizing="border-box",a.style.height="20px",a.style.width="100%",a.style.colorScheme="auto",a}var lr=class extends gt{constructor(e,a){super(e,a);k(this,"iframes");this.iframes=Jo(a.checkoutSessionId)}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:a}=await this.context.pciApi.postCardPaymentInstruments();if(e||!a)throw e??new z({code:F.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:O.PAYMENT_CARD});return a}};function Pu(r){if(!r)return{};let t=r.indexOf(" ");return t===-1?{firstName:r}:{firstName:r.substring(0,t),lastName:r.substring(t+1)}}function Li(r){let{firstName:t,lastName:e}=Pu(r.name);return{firstName:t||null,lastName:e||null,addressLine1:r.address1||null,addressLine2:r.address2||null,city:r.locality||null,state:r.administrativeArea||null,postalCode:r.postalCode||null,countryCode:r.countryCode||null}}function co(r){return r.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var uo=2,po=0,Nu="https://pay.google.com/gp/p/js/pay.js",Iu={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},mo=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],Xa={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},er={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},ku="buy",Lu="black",Ru="fill",dr=class extends gt{constructor(){super(...arguments);k(this,"disabled",!1);k(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,a){return this.context.translate?.(e,a)??a}async tokenize(){throw new z({code:F.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:O.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await Ho(Nu),!0}catch{return C.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:a}=this.context.configuration.clientSession.order;if(!e)throw new G({code:xt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:O.GOOGLE_PAY});if(!a)throw new G({code:xt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:O.GOOGLE_PAY});if(!await this.loadGooglePayScript())return C.error("Google Pay script failed to load"),!1;let n=this.context.configuration.env==="PRODUCTION"?"PRODUCTION":"TEST";this.client=new google.payments.api.PaymentsClient({environment:n,...this.needsPaymentDataCallbacks()&&{paymentDataCallbacks:{onPaymentDataChanged:s=>this.handlePaymentDataChanged(s)}}});try{let{result:s,paymentMethodPresent:l}=await this.client.isReadyToPay(this.buildIsReadyToPayRequest());if(!s)return C.info("Google Pay is not available in this browser/device"),!1;if(this.clientOptions?.existingPaymentMethodRequired&&l===!1)return C.info("Google Pay: existingPaymentMethodRequired is true but no existing payment method is available"),!1}catch(s){return C.error("Google Pay isReadyToPay check failed",{error:s}),!1}let o=this.context.onClientConfigurationUpdate(s=>{let l=s.clientSession?.order;(!l||!l.totalOrderAmount||!l.currencyCode)&&C.warn("Google Pay: Order details are missing or incomplete after client session update. Ensure order details (totalOrderAmount, currencyCode, countryCode) are always provided.")});return this.context.subscribeToTeardown(o),!0}needsPaymentDataCallbacks(){return!!(this.clientOptions?.requireShippingMethod||this.shouldCaptureShippingAddress)}buildIsReadyToPayRequest(){return{apiVersion:uo,apiVersionMinor:po,allowedPaymentMethods:[this.allowedPaymentMethod],existingPaymentMethodRequired:this.clientOptions?.existingPaymentMethodRequired}}async render(e){if(!this.client)return void C.error("Google Pay client not initialized. Call setup() first.");let a=this.client.createButton({buttonType:this.clientOptions?.buttonType??ku,buttonColor:this.clientOptions?.buttonColor??Lu,buttonSizeMode:this.clientOptions?.buttonSizeMode??Ru,buttonRadius:this.clientOptions?.buttonRadius,buttonLocale:this.clientOptions?.buttonLocale,buttonBorderType:this.clientOptions?.buttonBorderType,onClick:i=>this.handleClick(i),buttonRootNode:e instanceof ShadowRoot?e:void 0});e.appendChild(a)}async handleClick(e){if(!this.client)return void C.error("Google Pay client not available");let a=this.callbacks.onStart();wt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:O.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await a;if(n==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});await this.processPaymentData(i)}catch(i){if(i.statusCode==="CANCELED")return void this.context.clientSessionApi.unselectPaymentMethod();C.errorWithDatadog("Google Pay error",{error:i}),this.callbacks.onFinish(void 0,i)}}get clientOptions(){return this.context.clientOptions.googlePay}get shouldCaptureShippingAddress(){return!!(this.clientOptions?.captureShippingAddress||this.clientOptions?.shippingAddressParameters)}async processPaymentData(e){if(this.clientOptions?.captureBillingAddress&&await this.updateBillingAddress(e),(this.shouldCaptureShippingAddress||this.clientOptions?.requireShippingMethod||this.clientOptions?.emailRequired)&&await this.updateShippingDetails(e),this.clientOptions?.requireShippingMethod){let n=e.shippingOptionData?.id;n&&await this.context.clientSessionApi.selectShippingMethod(n)}let{data:a,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:rr.encode(e.paymentMethodData.tokenizationData.token)});if(i||!a)throw this.callbacks.onFinish(void 0,i),i??new z({code:F.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:O.GOOGLE_PAY});this.callbacks.onFinish(a)}async updateBillingAddress(e){let a=e.paymentMethodData.info?.billingAddress;if(a){let i=Li(a);await this.context.clientSessionApi.setBillingAddress(i)}else C.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let a=e.shippingAddress,i=e.email,n=a?.phoneNumber;if(a||n||i){let o=a?Li(a):void 0;await this.context.clientSessionApi.setShippingAddress(o,n,i)}else C.warn("Google Pay: No shipping address, phone number, or email found in payment data")}async handlePaymentDataChanged(e){let a=e.callbackTrigger;try{if(a==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(a==="SHIPPING_ADDRESS"||a==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=Li(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:co(o),defaultSelectedOptionId:n?.selectedShippingMethod||o[0]?.id}},newTransactionInfo:this.getCurrentTransactionInfo()}}return{newTransactionInfo:this.getCurrentTransactionInfo()}}catch(i){return C.errorWithDatadog("Google Pay: Error handling payment data change",{error:i}),{error:{reason:"OTHER_ERROR",message:"An error occurred while processing your request",intent:a==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:a,totalOrderAmount:i}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:a,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:ya(i,a),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:a,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(Xa.SUBTOTAL,er.SUBTOTAL),type:"SUBTOTAL",price:ya(i,a)}),c):(n&&n.length>0&&n.forEach(m=>{c.push({label:m.description||this.translate(Xa.ITEM,er.ITEM),type:"LINE_ITEM",price:ya(m.amount,a)})}),o&&o.length>0&&o.filter(m=>m.amount!==0).forEach(m=>{c.push({label:m.type||m.description||this.translate(Xa.FEE,er.FEE),type:"LINE_ITEM",price:ya(m.amount,a)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(Xa.SHIPPING,er.SHIPPING),type:"LINE_ITEM",price:ya(s.amount,a)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return mo;let a=e.map(i=>Iu[i]).filter(i=>!!i);return a.length>0?a:mo}get allowedPaymentMethod(){let e=this.clientOptions?.captureBillingAddress;return{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.allowedCardNetworks,...e&&{billingAddressRequired:!0,billingAddressParameters:{format:"FULL"}}}}}buildPaymentDataRequest(){let e=this.clientOptions?.shippingAddressParameters,a=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:uo,apiVersionMinor:po,...a&&{emailRequired:!0},...(this.shouldCaptureShippingAddress||i)&&{shippingAddressRequired:!0,...e&&{shippingAddressParameters:{...e.allowedCountryCodes&&{allowedCountryCodes:e.allowedCountryCodes},...e.phoneNumberRequired&&{phoneNumberRequired:!0}}}},...i&&{shippingOptionRequired:!0,...o&&o.length>0&&{shippingOptionParameters:{shippingOptions:co(o),defaultSelectedOptionId:s||o[0]?.id}}},...this.needsPaymentDataCallbacks()&&{callbackIntents:[...i?["SHIPPING_ADDRESS","SHIPPING_OPTION"]:["SHIPPING_ADDRESS"]]},transactionInfo:this.getCurrentTransactionInfo(),merchantInfo:{merchantId:this.config.options.merchantId,merchantName:this.config.options.merchantName},allowedPaymentMethods:[{...this.allowedPaymentMethod,tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"primer",gatewayMerchantId:this.config.options.merchantId}}}]}}};function _u(r,t){var e={};for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&t.indexOf(a)<0&&(e[a]=r[a]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,a=Object.getOwnPropertySymbols(r);i<a.length;i++)t.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(r,a[i])&&(e[a[i]]=r[a[i]]);return e}function xu(r,t){var e=document.querySelector('script[src="'.concat(r,'"]'));if(e===null)return null;var a=qo(r,t),i=e.cloneNode();if(delete i.dataset.uidAuto,Object.keys(i.dataset).length!==Object.keys(a.dataset).length)return null;var n=!0;return Object.keys(i.dataset).forEach(function(o){i.dataset[o]!==a.dataset[o]&&(n=!1)}),n?e:null}function wu(r){var t=r.url,e=r.attributes,a=r.onSuccess,i=r.onError,n=qo(t,e);n.onerror=i,n.onload=a,document.head.insertBefore(n,document.head.firstElementChild)}function Du(r){var t=r.sdkBaseUrl,e=r.environment,a=_u(r,["sdkBaseUrl","environment"]),i=t||Gu(e),n=a,o=Object.keys(n).filter(function(c){return n[c]!==void 0&&n[c]!==null&&n[c]!==""}).reduce(function(c,m){var g=n[m].toString();return m=Ou(m),m.substring(0,4)==="data"||m==="crossorigin"?c.attributes[m]=g:c.queryParams[m]=g,c},{queryParams:{},attributes:{}}),s=o.queryParams,l=o.attributes;return s["merchant-id"]&&s["merchant-id"].indexOf(",")!==-1&&(l["data-merchant-id"]=s["merchant-id"],s["merchant-id"]="*"),{url:"".concat(i,"?").concat(Bu(s)),attributes:l}}function Ou(r){var t=function(e,a){return(a?"-":"")+e.toLowerCase()};return r.replace(/[A-Z]+(?![a-z])|[A-Z]/g,t)}function Bu(r){var t="";return Object.keys(r).forEach(function(e){t.length!==0&&(t+="&"),t+=e+"="+r[e]}),t}function Gu(r){return r==="sandbox"?"https://www.sandbox.paypal.com/sdk/js":"https://www.paypal.com/sdk/js"}function qo(r,t){t===void 0&&(t={});var e=document.createElement("script");return e.src=r,Object.keys(t).forEach(function(a){e.setAttribute(a,t[a]),a==="data-csp-nonce"&&e.setAttribute("nonce",t["data-csp-nonce"])}),e}function Ku(r,t){if(t===void 0&&(t=Promise),Qo(r,t),typeof document>"u")return t.resolve(null);var e=Du(r),a=e.url,i=e.attributes,n=i["data-namespace"]||"paypal",o=ho(n);return i["data-js-sdk-library"]||(i["data-js-sdk-library"]="paypal-js"),xu(a,i)&&o?t.resolve(o):Fu({url:a,attributes:i},t).then(function(){var s=ho(n);if(s)return s;throw new Error("The window.".concat(n," global variable is not available."))})}function Fu(r,t){t===void 0&&(t=Promise),Qo(r,t);var e=r.url,a=r.attributes;if(typeof e!="string"||e.length===0)throw new Error("Invalid url.");if(a!==void 0&&typeof a!="object")throw new Error("Expected attributes to be an object.");return new t(function(i,n){if(typeof document>"u")return i();wu({url:e,attributes:a,onSuccess:function(){return i()},onError:function(){var o=new Error('The script "'.concat(e,'" failed to load. Check the HTTP status code and response body in DevTools to learn more.'));return n(o)}})})}function ho(r){return window[r]}function Qo(r,t){if(typeof r!="object"||r===null)throw new Error("Expected an options object.");var e=r.environment;if(e&&e!=="production"&&e!=="sandbox")throw new Error('The `environment` option must be either "production" or "sandbox".');if(t!==void 0&&typeof t!="function")throw new Error("Expected PromisePonyfill to be a function.")}var tr=new Map,go={getOrCreateNamespace(r){let t=tr.get(r);return t?t.namespace:Pe()},getInstance(r){return tr.get(r)?.instance??null},storeInstance(r,t,e){tr.set(r,{instance:t,namespace:e})},hasInstance(r){return tr.has(r)}};async function Vu({context:r,configId:t,paymentMethodType:e,callbacks:a}){try{let{action:i}=await a.onStart();if(i==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e});let{data:n,error:o}=await r.coreApi.createPaypalBillingAgreement({paymentMethodConfigId:t});if(o||!n){let s=o?.message??"Failed to create billing agreement";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.tokenId}catch(i){throw C.errorWithDatadog("PayPal billing agreement creation failed:",{error:i}),a.onFinish(void 0,i),i instanceof G||i instanceof z?i:new G({message:"Failed to create billing agreement",code:F.PAYMENT_FAILED,paymentMethod:e})}}async function Uu({context:r,configId:t,paymentMethodType:e,callbacks:a,data:i}){try{let n=i.billingToken;if(!n)throw new z({message:"Billing token not provided",code:F.TOKENIZATION_ERROR,paymentMethod:e});let{data:o,error:s}=await r.coreApi.confirmPaypalBillingAgreement({paymentMethodConfigId:t,tokenId:n});if(s||!o){let h=s?.message??"Failed to confirm billing agreement";throw new z({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}let l=o,c={paypalBillingAgreementId:l.billingAgreementId,shippingAddress:l.shippingAddress,externalPayerInfo:l.externalPayerInfo},{error:m,data:g}=await r.pciApi.postPaypalPaymentInstruments(c,{tokenType:"MULTI_USE",paymentFlow:"VAULT"});if(m||!g){let h=m?.message??"Unable to vault PayPal payment method";throw new z({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}a.onFinish(g)}catch(n){throw C.errorWithDatadog("PayPal billing agreement approval failed:",{error:n}),a.onFinish(void 0,n),n instanceof z||n instanceof G?n:new z({message:"Failed to approve billing agreement",code:F.TOKENIZATION_ERROR,paymentMethod:e})}}var Hu="gold",Yu="black",$u="rect",zu="paypal",ju="vertical",Xo="horizontal",yo=2,fo=["paypal","paylater"],es={default:{color:Hu},card:{validColors:["black","white"],defaultColor:Yu}};function Wu(r){if(!r)return;let t=es[r];if(t&&"validColors"in t)return t}function Zu(r,t){let e=Wu(t);if(!e)return r??es.default.color;let a=r??e.defaultColor;return e.validColors.includes(a)?a:(C.warn(`PayPal: Invalid color "${a}" for ${t} button. Only supports: ${e.validColors.join(", ")}. Falling back to "${e.defaultColor}".`),e.defaultColor)}var Ju=25,qu=55;function Qu(r){return parseFloat(r)||0}function Xu(r){let t=Qu(r);return Math.max(Ju,Math.min(qu,t))}function ep(r,t,e){let a=t?r?.[t]:void 0,i=a?.tagline??r?.tagline??!1,n=i?Xo:ju,o,s=a?.height??r?.height;s!=null?o=s:e!=null&&(o=Xu(String(e)));let l=a?.borderRadius??r?.borderRadius,c=a?.disableMaxWidth??r?.disableMaxWidth,m=a?.color??r?.color;return{color:Zu(m,t),shape:a?.shape??r?.shape??$u,label:a?.label??r?.label??zu,layout:a?.layout??r?.layout??n,tagline:i,...o!=null&&{height:o},...l!=null&&{borderRadius:l},...c!=null&&{disableMaxWidth:c}}}function tp(r,t,e,a){let i={style:r,onInit:e.onInit,onClick:e.onClick,onCancel:e.onCancel,onError:e.onError};return t&&a?(i.createBillingAgreement=a.createBillingAgreement,i.onApprove=a.onApprove):i.onApprove=e.onApprove,i}function ap(r){if(!r)return;let t={first_name:r.firstName,last_name:r.lastName,address_line_1:r.addressLine1??"",address_line_2:r.addressLine2,city:r.city??"",state:r.state,postal_code:r.postalCode??"",country_code:r.countryCode??""},{address_line_1:e,city:a,postal_code:i,country_code:n}=t;if(!(!e||!a||!i||!n))return t}function rp(r){if(!r)return null;let t=r.purchase_units?.[0]?.shipping;if(!t?.address)return null;let e=t.address,a=t.name;return{firstName:a?.given_name,lastName:a?.surname,addressLine1:e.address_line_1,addressLine2:e.address_line_2,city:e.admin_area_2,state:e.admin_area_1,postalCode:e.postal_code,countryCode:e.country_code}}function ip(r,t,e){let{order:{currencyCode:a,merchantAmount:i,totalOrderAmount:n,shipping:o,lineItems:s=[],fees:l=[]},customer:c}=r;if(!a)throw new G({message:"Currency code is not provided",code:xt.MISSING_PARAMETER,paymentMethod:e});let m={amount:i??n,currencyCode:a,paymentMethodConfigId:t,amountBreakdown:{}},g=c?.shippingAddress,h=ap(g);h&&(m.shipping_address=h);let T=!s.some(M=>!M.name&&!M.description);if(T&&(m.items=s.map(M=>{let{name:x,description:_,taxAmount:E,amount:L,quantity:K}=M,j=E?Math.floor(E/K):0;return{name:_||x||"",unit_amount:{value:L,currency_code:a},quantity:K.toString(),tax:{value:j,currency_code:a}}})),T&&s.length){let M=s.reduce((ce,{amount:V,quantity:Be})=>ce+V*Be,0),x=l?.reduce?.((ce,{amount:V})=>ce+(V??0),0),_=s?.reduce((ce,{discountAmount:V})=>ce+(V??0),0),E=s?.reduce((ce,{taxAmount:V})=>ce+(V??0),0),L=o?.amount??0,K=x??0,j=M+E+L+K-_;m.amountBreakdown={item_total:{value:M,currency_code:a},tax_total:{value:E,currency_code:a},handling:{value:K,currency_code:a},shipping:{value:L,currency_code:a},discount:{value:_,currency_code:a}},m.amount=j}return m}async function np({context:r,configId:t,paymentMethodType:e,callbacks:a,skipOnStartCallback:i=!1}){try{if(!i){let{action:s}=await a.onStart();if(s==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e})}let{data:n,error:o}=await r.coreApi.createPaypalOrder(ip(r.configuration.clientSession,t,e));if(o||!n){let s=o?.message??"Unable to create PayPal order";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.orderId}catch(n){throw a.onFinish(void 0,n),n}}async function op({context:r,paymentMethodType:t,callbacks:e,data:a,actions:i,deferredOnStartCallback:n=!1}){if(n){let{action:g}=await e.onStart();if(g==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:t})}let o=null;try{o=await i?.order?.get()??null}catch(g){C.warn("Failed to get PayPal order details",g)}let s=rp(o),l={external_payer_info:{email:o?.payer?.email_address,external_payer_id:a.payerID??void 0,first_name:o?.payer?.name?.given_name,last_name:o?.payer?.name?.surname},paypal_order_id:a.orderID,paypal_status:o?.status};s&&(l.shipping_address=s);let{error:c,data:m}=await r.pciApi.postPaypalPaymentInstruments(l);if(c||!m){let g=c?.message??"Unable to create payment instrument";throw new z({message:g,code:F.TOKENIZATION_ERROR,paymentMethod:t})}e.onFinish(m)}var sp=["buttons","funding-eligibility"],vo=[],So="paypal";function ts(r){if(!r?.length)return;r.includes(So)&&C.warn("PayPal: Cannot disable paypal funding source");let t=r.filter(e=>e!==So);return t.length>0?t:void 0}var lp="authorize";function dp(r,t,e){return(r??t==="PREFER_VAULT")&&e}function bo({isVaultFlow:r,configIntent:t}){return r?"tokenize":t??lp}function cp(r,t,e,a){let{clientId:i,intent:n}=t.options,o=r.configuration.clientSession.order.currencyCode,s=r.clientOptions.paypal?.disableFunding??(vo.length>0?vo:void 0),l=ts(s),c=r.clientOptions?.paypal?.enableFunding,m={dataNamespace:e,clientId:i,currency:o,components:sp,...l&&l.length>0?{disableFunding:l}:{},...c&&c.length>0?{enableFunding:c}:{},integrationDate:r.clientOptions.paypal?.integrationDate,debug:r.clientOptions.paypal?.debug};return(Fi||r.decodedClientToken.env==="SANDBOX"||r.decodedClientToken.env==="STAGING")&&(m.buyerCountry=r.clientOptions?.paypal?.buyerCountry),a?(m.vault="true",m.intent=bo({isVaultFlow:!0,configIntent:n})):(m.vault="false",m.intent=bo({isVaultFlow:!1,configIntent:n})),m}var cr=class extends gt{constructor(e,a){super(e,a);k(this,"paypalInstance");k(this,"dataNamespace");k(this,"isVaultFlow",!1);k(this,"isSetupComplete",!1);k(this,"setupPromise");k(this,"eligibleFundingSources",[]);k(this,"currentFundingSource",null);k(this,"onStartDeferred",!1);k(this,"disabled",!1);this.dataNamespace=go.getOrCreateNamespace(e.id),this.context.onClientConfigurationUpdate(async()=>{C.info("PayPal: Client session updated, refreshing PayPal buttons");try{await this.setup()}catch(i){C.warn("PayPal: Failed to refresh on client session update:",i)}})}async setDisabled(e){this.disabled=e}async tokenize(){throw new z({message:"PayPal does not support direct tokenization",code:F.TOKENIZATION_ERROR,paymentMethod:O.PAYPAL})}async setup(){let{clientId:e}=this.config.options;return this.setupPromise?(C.info("PayPal setup already in progress, waiting..."),this.setupPromise):this.isSetupComplete&&this.paypalInstance?.Buttons?(C.info("PayPal setup already completed, skipping"),!0):e?(this.setupPromise=(async()=>{try{let a=this.context.clientOptions.paypal?.vault,i=this.context.clientOptions.paypal?.paymentFlow,n=this.context.configuration.clientSession.paymentMethod?.vaultOnSuccess??!1;this.isVaultFlow=dp(a,i,n);let o=cp(this.context,this.config,this.dataNamespace,this.isVaultFlow);C.debug("%c PAYPAL %c Script Configuration ","background: #0070BA; color: #ffffff; font-weight: bold; padding: 4px 12px; border-radius: 3px 0 0 3px; font-size: 14px;","background: #003087; color: #ffffff; padding: 4px 12px; border-radius: 0 3px 3px 0; font-size: 14px;",o);let s=await Ku(o);if(!s)return C.warn("Failed to load PayPal SDK"),!1;this.paypalInstance=s,go.storeInstance(this.config.id,s,this.dataNamespace);let l=this.context.clientOptions.paypal?.enableFunding,c=ts(this.context.clientOptions.paypal?.disableFunding),g=(s.getFundingSources?.()??[]).filter(h=>s?.isFundingEligible?.(h));return C.debug("PayPal: Eligible funding sources from PayPal SDK:",g),this.eligibleFundingSources=this.filterFundingSources(g,l,c),(l?.length||c?.length)&&(C.debug("PayPal: Primer SDK options:",{enableFunding:l??[],disableFunding:c??[]}),C.debug("PayPal: Funding sources after Primer SDK filter:",this.eligibleFundingSources)),this.eligibleFundingSources.length===0?(C.warn("PayPal: No funding sources are eligible with current configuration"),!1):!0}catch(a){return C.warn("PayPal setup failed:",{error:a}),this.setupPromise=void 0,!1}})(),this.setupPromise):(C.warn("PayPal clientId is required"),!1)}async render(e,a){let{Buttons:i}=this.paypalInstance;if(!i)throw new G({message:"PayPal Buttons component not available",code:xt.INVALID_USAGE,paymentMethod:O.PAYPAL});let n=this.context.clientOptions.paypal?.style,o=a?.style?.buttonHeight,s=n?.layout===Xo,l={onInit:this.handleInit.bind(this),onClick:this.handleClick.bind(this),onApprove:this.handleApprove.bind(this),onCancel:this.handleCancel.bind(this),onError:this.handleError.bind(this)},c=this.isVaultFlow?{createBillingAgreement:()=>Vu({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks}),onApprove:M=>Uu({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,data:M})}:void 0,m=this.eligibleFundingSources,g=[];for(let M of m){let x=ep(n,M,o),_=tp(x,this.isVaultFlow,l,c);this.isVaultFlow||(_.createOrder=this.handleCreateOrder.bind(this));let E=i({..._,fundingSource:M});E.isEligible()?g.push({button:E,fundingSource:M}):C.debug(`PayPal: Button for "${M}" is not eligible with current config`)}if(g.length===0)throw C.warn("PayPal: No buttons were eligible to render with current configuration"),new G({message:"No PayPal buttons eligible to render",code:xt.INVALID_USAGE,paymentMethod:O.PAYPAL});let h=s&&g.length>yo?this.selectButtonsForHorizontalLayout(g):g;s&&this.applyHorizontalLayoutStyles(e,h.length);let T=h.map(({button:M})=>M.render(e));await Promise.all(T)}selectButtonsForHorizontalLayout(e){let a=new Set(fo),i=fo.map(o=>e.find(s=>s.fundingSource===o)).filter(o=>o!==void 0),n=e.filter(o=>!a.has(o.fundingSource));return[...i,...n].slice(0,yo)}applyHorizontalLayoutStyles(e,a){e.style.display="grid",e.style.gridTemplateColumns=`repeat(${a}, 1fr)`,e.style.gap="10px"}handleInit(e,a){let{clientSession:i}=this.context.configuration,n=!!i.order.currencyCode,o=!!i.order.totalOrderAmount||!!i.order.merchantAmount;if(!n||!o){C.warn("PayPal button disabled: missing currency or amount"),a.disable();return}a.enable()}handleClick(e,a){return this.currentFundingSource=e.fundingSource??null,wt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYPAL"}),a.resolve()}async handleCreateOrder(){let e=this.currentFundingSource==="card";return this.onStartDeferred=e,np({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,skipOnStartCallback:e})}async handleApprove(e,a){let i=this.onStartDeferred;return this.onStartDeferred=!1,op({context:this.context,paymentMethodType:this.config.type,callbacks:this.callbacks,data:e,actions:a,deferredOnStartCallback:i})}handleCancel(){this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,new G({message:"The PayPal payment was cancelled by the user.",paymentMethod:O.PAYPAL}))}handleError(e){C.errorWithDatadog("PayPal error:",e),this.callbacks.onFinish(void 0,e)}filterFundingSources(e,a,i){return e.filter(n=>!(a?.length&&!a.includes(n)||i?.includes(n)))}};function Ao(r,t,e){if(!r)return null;let a={id:r.id,orderId:r.orderId};return t?.paymentInstrumentData&&e&&(a.paymentMethodData={paymentMethodType:e,...t.paymentInstrumentData}),a}var as=(r,t,e,a,i)=>{let n=e;if(t?.status==="FAILED"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.checkoutOutcome==="CHECKOUT_FAILURE"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="PENDING"&&!t.requiredAction?.clientToken&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" ended up in a "PENDING" state without any required action. The SDK does not know how to handle this state. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="SUCCESS"&&t.checkoutOutcome!=="CHECKOUT_FAILURE"||t?.status==="PENDING"&&t.showSuccessCheckoutOnPendingPayment||t?.checkoutOutcome==="CHECKOUT_COMPLETE")return void r.onCheckoutComplete?.({payment:Ao(t,a,i)});r.onCheckoutFail?.(n||new G({code:F.PAYMENT_FAILED,message:`The payment${t?.id?` "${t.id}"`:""} is in an inconsistent state without any required action. The SDK does not know how to handle this state. Please contact Primer.`}),{payment:Ao(t,a,i)??void 0})},up=async(r,t)=>{let e=t.config.type;if(!r.onBeforePaymentCreate)return{action:"continue"};let a=setTimeout(()=>{C.warn("onBeforePaymentCreate did not resolve within 10 seconds. Primer SDK will remain in a loading state until `continuePaymentCreation` or `abortPaymentCreation` is called.")},1e4);return new Promise(i=>{r.onBeforePaymentCreate({paymentMethodType:e},{continuePaymentCreation:n=>{clearTimeout(a),C.log(`Continuing payment creation for ${e}`),n?.idempotencyKey&&t.setIdempotencyKey(n.idempotencyKey),r.onPaymentCreationStart?.(),i({action:"continue"})},abortPaymentCreation:()=>{clearTimeout(a),C.log(`Aborting payment creation for ${e}`),i({action:"abort"})}})})};async function Ca(r,t,e){if(t.setCallbacks({onStart:()=>(t.context.clientSessionApi.selectPaymentMethod(t.config.type),wt({eventName:"PAYMENT_PROCESSING_STARTED",paymentMethod:t.config.type}),up(r,t)),onFinish:(a,i)=>{Co(r,t,a,i)}}),!e)return t.start();{let a,i;try{i=await t.tokenizeVaulted(e.id)}catch(n){a=n}return Co(r,t,i,a)}}async function Co(r,t,e,a){let i;if(e&&!a)try{if(i=await t.createPayment(e),i.cancelled)return;i.status!=="FAILED"&&(i=await t.handleRequiredAction(i))}catch(n){a=n}as(r,i,a,e,t.config.type)}var Mo=Symbol("PROXY_MARKER");function Xi({namespace:r,onMessage:t,sendMessage:e}){function a(i,n){return new Proxy(i,{get(o,s,l){if(s==="then")return null;if(o[Mo])return Reflect.get(o,s,l);let c=()=>{};return c[Mo]=!0,a(c,[...n,s])},apply(o,s,l){return new Promise(async(c,m)=>{try{let g=[],h=l.map(_=>{if(typeof _!="function")return _;{let E=Pe();return g.push(E),t(L=>{L.namespace===r&&L.sender===_i.PROVIDER&&L.type===Ri.CALLBACK&&L.id===E&&_(...L.data)}),E}}),T=Pe(),M=t(_=>{_.namespace===r&&_.sender===_i.PROVIDER&&_.type===Ri.APPLY&&_.id===T&&(_.error?m(new Error(_.error)):c(_.data),M?.())}),x={type:Ri.APPLY,sender:_i.INJECTOR,id:T,path:n,args:h,callbackIds:g,timeStamp:Date.now(),namespace:r};e(x)}catch(g){m(g)}})}})}return a({},[])}var Ri={APPLY:"apply",CALLBACK:"callback"},_i={PROVIDER:"provider",INJECTOR:"injector"};function Vi(r,t){let e=t?.input?.base?.height;e&&(r.style.height=typeof e=="number"?`${e}px`:e)}function pp(r,t,e,a={}){let i=r.cardholderName?.defaultValue??r.card?.cardholderName?.defaultValue,n=Jo(t.checkoutSessionId,{cardholderName:i});e.iframes=n;let o=[],s="LOCAL",l={[ue.cardNumber]:void 0,[ue.cardExpiryDate]:void 0,[ue.cardSecurityCode]:void 0,[ue.cardholderName]:void 0},c=!1;t.subscribeToTeardown(()=>{c=!0});let m={createHostedInputs:()=>{let g=h=>{let T=new Map;return{getOptions:()=>{},setOptions:M=>{Vi(e.iframes[h],M.style),e.iframes[h].setAttribute("title",M.ariaLabel||""),l[h]?.setOptions(M)},render:(M,x)=>{let _=e.iframes[h];if(!_)return C.errorWithDatadog(`No iframe found for ${h}`),Promise.resolve();let E;return E=typeof M=="string"?document.getElementById(M):M,E?(Vi(_,x.style),E.appendChild(_),new Promise(L=>{_.onload=()=>{if(c){C.warn(`Teardown was already called, aborting render for ${h}`),_.remove(),L();return}l[h]=Xi({namespace:`${t.checkoutSessionId}-${h}`,onMessage:V=>{let Be=ga=>V(ga.data);return window.addEventListener("message",Be),()=>window.removeEventListener("message",Be)},sendMessage:V=>{_.contentWindow.postMessage(V,"*")}}),e.iframes[h].setAttribute("title",x.ariaLabel||"");let K=r.cardholderName??r.card?.cardholderName,{defaultValue:j,...ce}=K??{};l[h].setOptions({...x,orderedAllowedCardNetworks:t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks,cardholderName:ce}),l[h].setBinDataLoadingChange(V=>{V&&a.onCardNetworksLoading?.(),a.onBinDataLoadingChange?.(V)}),l[h].setOnBlur(()=>{try{T.get("blur")?.()}catch(V){C.errorWithDatadog(`Blur listener error for ${h}`,{error:V})}}),l[h].setOnFocus(()=>{try{T.get("focus")?.()}catch(V){C.errorWithDatadog(`Focus listener error for ${h}`,{error:V})}}),l[h].setOnInput(V=>{let Be={...V,errorCode:V.error,active:V.focused};try{T.get("input")?.(Be),T.get("change")?.(Be)}catch(ga){C.errorWithDatadog(`Input listener error for ${h}`,{error:ga})}}),l[h].setOnEnter(()=>{try{T.get("enter")?.()}catch(V){C.errorWithDatadog(`Enter listener error for ${h}`,{error:V})}}),h===ue.cardNumber&&(l[h].setBinDataApiConfig(t.configuration.binDataUrl,t.decodedClientToken.accessToken),l[h].setOnCardNetworksChange((V,Be,ga)=>{if(Be!==s||mp(o,V)){o=V,s=Be;let{cardNetworkChangeEventData:kc,binDataAvailableEventData:Lc}=Tu({networks:o,source:s},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks);a.onCardNetworksChange?.(kc),a.onBinDataAvailable?.({...Lc,firstDigits:ga})}}))},L()})):(C.error(`Container not found for ${h}:`,M),Promise.resolve())},addEventListener:(M,x)=>{T.set(M,x)},focus:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.focus()}catch(x){C.errorWithDatadog(`Focus send error for ${h}`,{error:x})}else C.warn(`Focus failed for ${h} - iframe not available`)},blur:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.blur()}catch(x){C.errorWithDatadog(`Blur send error for ${h}`,{error:x})}},setDisabled:M=>{l[h]?.setDisabled(M)}}};return{cardNumberInput:g(ue.cardNumber),cardholderNameInput:g(ue.cardholderName),expiryInput:g(ue.cardExpiryDate),cvvInput:g(ue.cardSecurityCode)}},removeHostedInputs:()=>{c=!0,e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardholderName.remove()},submit:async g=>{if((await m.validate()).valid)return await t.apiController.setPreferredNetwork(g?.cardNetwork),Ca(r,e)},validate:async()=>{let g=(await Promise.all(Object.entries(l).map(([T,M])=>M?.getFieldState().then(x=>[T,x]).catch(()=>{})))).filter(T=>T!==void 0),h=[];for(let[T,M]of g)!M.valid&&M.error&&h.push({field:T,name:T,error:M.error,message:M.error});return{valid:h.length===0,validationErrors:h}},reset:()=>{Object.values(l).forEach(g=>{g?.reset()}),t.apiController.setPreferredNetwork(void 0)},setCardholderName:g=>{try{l[ue.cardholderName]?.setCardholderName(g)}catch(h){C.errorWithDatadog("SetCardholderName error",{error:h})}}};return m}function mp(r,t){if(r.length!==t.length)return!0;let e=t.map(({network:a})=>a);return!r.every(({network:a})=>e.includes(a))}function hp(r,t,e){return{createButton:()=>({render:async(a,i)=>{await Ca(r,e);let n=typeof a=="string"?document.getElementById(a):a;if(!n)throw new G({code:ou.CONTAINER_NOT_FOUND,message:`Container with id "${a}" not found in the DOM.`});await e.render(n,i)},setDisabled:a=>e.setDisabled(a)})}}function gp(r,t,e){return{start:()=>Ca(r,e)}}function yp(r,t,e){return{start:async a=>(a?.blikCode&&e.setBlikCode(a.blikCode),Ca(r,e))}}function fp(r,t){return{"Content-Type":"application/json","primer-client-token":r,"primer-sdk-client":"WEB","primer-sdk-version":"0.0.0-local","primer-sdk-checkout-session-id":t,"x-api-version":"2.4"}}function vp(r,t,e){if(e?.status&&e.status>=400&&e.status<500)return!1;if(e?.status&&e.status>=500)return!0;if(r instanceof Error){let a=r.message.toLowerCase();return a.includes("network")||a.includes("timeout")||a.includes("connection")}return!1}function Sp(r){let n=1e3*Math.pow(1.1,r),o=.1*n*(Math.random()-.5);return n=Math.max(0,n+o),Math.min(n,3e4)}var bp={attempts:3,retryCondition:vp,delayCalculator:Sp,totalTimeout:3e5};async function Ap(r,t,e){let a={...bp,...t.retry},i=[],n=Date.now();for(let s=0;s<=a.attempts;s++)try{let l=await r();if(!l.error)return{...l,retryHistory:i.length>0?i:void 0};if(s===a.attempts||!a.retryCondition(l.error,s,l))return{...l,retryHistory:i};let c=a.delayCalculator(s);if(i.push({attempt:s+1,delay:c,error:l.error,timestamp:Date.now()}),Date.now()-n+c>a.totalTimeout)return{...l,error:new Ge({message:`Retry total timeout exceeded for ${t.method} ${e}`,code:Aa({status:408}),response:l}),retryHistory:i};await qt(c)}catch(l){i.push({attempt:s+1,delay:0,error:new Ge({message:`Request failed for ${t.method} ${e}`,code:Q.UNEXPECTED,error:l,response:{id:t.id}}),timestamp:Date.now()})}let o=i[i.length-1]?.error;return{id:t.id,error:o,retryHistory:i}}var Xt=class{constructor(t,e="",a={}){k(this,"fetch");k(this,"baseUrl");k(this,"defaultHeaders");this.fetch=t,this.baseUrl=e,this.defaultHeaders=Object.freeze({...a})}setDefaultHeader(t,e){this.defaultHeaders={...this.defaultHeaders,[t]:e}}async executeFetch(t,e){let a={...e,headers:{...this.defaultHeaders,...e?.headers},id:Pe()};return e?.retry?Ap(()=>this.fetch(t,{...a,retry:void 0}),a,t):this.fetch(t,a)}async get(t,e){return this.executeFetch(t,{...e,method:"GET"})}async post(t,e,a){return this.executeFetch(t,{...a,method:"POST",body:JSON.stringify(e)})}async delete(t,e){return this.executeFetch(t,{...e,method:"DELETE"})}};async function Cp(r,t){let e=t.id??Pe(),a={id:e};t.headers??(t.headers={}),t.headers["X-Request-Id"]=e;try{let i=await fetch(r,t);if(a.data=await i.json(),a.status=i.status,a.headers=Object.fromEntries(i.headers.entries()),!i.ok){let n=new Ge({message:`Request failed for ${t.method} ${r}`,code:Aa({backendErrorId:a.data?.error?.errorId,status:a.status}),response:{...a}});a.error=n}}catch(i){let n=new Ge({message:`Request failed for ${t.method} ${r}`,code:Aa({status:a.status}),response:{...a},error:i});a.error=n}return a}var Ui=class extends Xt{constructor(){super(...arguments);k(this,"configurationSubscribers",new Set);k(this,"_configuration")}async getConfiguration(){let e=await this.get(this.baseUrl);return e.data&&(this._configuration=e.data),e}subscribe(e){return this.configurationSubscribers.add(e),()=>{this.configurationSubscribers.delete(e)}}get configuration(){return this._configuration}set configuration(e){this._configuration=e,this.configurationSubscribers.forEach(a=>a(this._configuration))}},Hi=class extends Xt{async getPaymentInstruments(){return this.get(`${this.baseUrl}/payment-instruments`)}async postCardPaymentInstruments(){return this.post(`${this.baseUrl}/payment-instruments`,"pci-card-form-data")}async postPaypalPaymentInstruments(t,e){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,...e})}async postPaymentInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t})}async postRedirectPaymentInstruments(t){return this.postPaymentInstruments(t)}async postApplePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postGooglePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postBlikPaymentInstruments(t){return this.postPaymentInstruments(t)}async postPaymentInstrumentsExchange(t){return this.post(`${this.baseUrl}/payment-instruments/${t}/exchange`,"payment-instrument-exchange")}async postCreatePayment(t,e){return this.post(`${this.baseUrl}/payments`,{paymentMethodToken:t},e?{headers:{"X-Idempotency-Key":e}}:void 0)}async postResumePayment(t,e){return this.post(`${this.baseUrl}/payments/${t}/resume`,{resumeToken:e})}async post3dsAuth(t,e){return this.post(`${this.baseUrl}/3ds/${t}/auth`,e,{retry:{attempts:15}})}async post3dsContinue(t){return this.post(`${this.baseUrl}/3ds/${t}/continue`,{platform:"WEB",status:"FAILURE"})}async get3dsResumeStatus(t){return this.get(t)}async deletePaymentInstrument(t){return this.delete(`${this.baseUrl}/payment-instruments/${t}/vault`)}async postClientSessionActions(t){return this.post(`${this.baseUrl}/client-session/actions`,{actions:t})}async getResumeStatus(t){return this.get(t)}};async function Mp(r){return new Promise((t,e)=>{let a=Zo(r,"api"),i=`${Cu}#${a}`,n=document.querySelector(`iframe[src="${i}"]`)??document.createElement("iframe");n.parentElement?t(n):(n.style.display="none",n.onload=()=>t(n),n.onerror=o=>{e(new Error(`Failed to initialize Primer SDK: ${o}`))},n.src=i,document.body.appendChild(n))})}var _t=class _t extends Xt{constructor(){super(...arguments);k(this,"onClientSessionUpdate");k(this,"onPaymentMethodAction");k(this,"selectedPaymentMethodType",null)}setOnClientSessionUpdate(e){this.onClientSessionUpdate=e}setOnPaymentMethodAction(e){this.onPaymentMethodAction=e}async postClientSessionActions(e){if(e.length===0)return _t.noActionsResponse;let a=await this.post(`${this.baseUrl}/client-session/actions`,{actions:e}),{data:i}=a;return i&&this.onClientSessionUpdate?.(i),a}async selectPaymentMethod(e,a={}){return this.selectedPaymentMethodType===e||(this.selectedPaymentMethodType=e,this.onPaymentMethodAction?.("PAYMENT_METHOD_SELECTED",{paymentMethodType:e}),e==="PAYMENT_CARD"&&!a.binData)?_t.noActionsResponse:this.postClientSessionActions([{type:"SELECT_PAYMENT_METHOD",params:{...a,paymentMethodType:e}}])}async unselectPaymentMethod(){return this.onPaymentMethodAction?.("PAYMENT_METHOD_UNSELECTED",{paymentMethodType:this.selectedPaymentMethodType}),this.selectedPaymentMethodType=null,this.postClientSessionActions([{type:"UNSELECT_PAYMENT_METHOD"}])}async selectCardNetwork(e){return this.selectPaymentMethod(O.PAYMENT_CARD,{binData:this.buildCardBinData(e)})}async setBillingAddress(e){let a=this.removeEmptyStringFromObject(e);return Object.values(a).length===0?_t.noActionsResponse:this.postClientSessionActions([{type:"SET_BILLING_ADDRESS",params:{billingAddress:a}}])}async setShippingAddress(e,a,i){let n=[];return e&&Object.keys(e).some(s=>!!e[s])&&n.push({type:"SET_SHIPPING_ADDRESS",params:{shippingAddress:e}}),a&&n.push({type:"SET_MOBILE_NUMBER",params:{mobileNumber:a}}),i&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:i}}),this.postClientSessionActions(n)}async selectShippingMethod(e){return this.postClientSessionActions([{type:"SELECT_SHIPPING_METHOD",params:{shippingMethodId:e}}])}async setCustomerDetails({emailAddress:e,firstName:a,lastName:i}){let n=[];return e&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:e}}),a&&n.push({type:"SET_CUSTOMER_FIRST_NAME",params:{firstName:a}}),i&&n.push({type:"SET_CUSTOMER_LAST_NAME",params:{lastName:i}}),this.postClientSessionActions(n)}buildCardBinData(e){let{backend:a}=ur(e);return{network:a,issuer_name:null,product_code:a,product_name:a,product_usage_type:"UNKNOWN",account_number_type:"UNKNOWN",issuer_country_code:null,account_funding_type:"UNKNOWN",issuer_currency_code:null,regional_restriction:"UNKNOWN",prepaid_reloadable_indicator:"NOT_APPLICABLE"}}removeEmptyStringFromObject(e){let a={...e};for(let i in a)a[i]===""?delete a[i]:typeof a[i]=="object"&&a[i]!==null&&!Array.isArray(a[i])&&(a[i]=this.removeEmptyStringFromObject(a[i]));return a}};k(_t,"noActionsResponse",{data:{},error:void 0,headers:{},status:200,id:""});var Yi=_t,$i=class extends Xt{async createPaypalOrder(t){return this.post(`${this.baseUrl}/paypal/orders/create`,t,{retry:{attempts:3}})}async createPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/create-agreement`,t,{retry:{attempts:3}})}async confirmPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/confirm-agreement`,t,{retry:{attempts:3}})}async createApplePaySession(t){return this.post(`${this.baseUrl}/apple-pay/sessions`,t)}};async function Ep(r,{locale:t,dialogProvider:e,translate:a,clientOptions:i}){let n=Pe(),o=Jt(r),s=await Mp(n),l=Xi({namespace:`api-controller-${n}`,onMessage:E=>{let L=K=>{if(K.data?.data?.error?.name==="RequestError"){let j=Object.assign(new Ge({...K.data.data.error}),K.data.data.error);typeof j.error=="object"&&"message"in j.error&&(j.error=Object.assign(new Error(j.error.message),{stack:j.error.stack})),K.data.data.error=j}return E(K.data)};return window.addEventListener("message",L),()=>window.removeEventListener("message",L)},sendMessage:E=>{s.contentWindow.postMessage(E,"*")}}),c=fp(o.accessToken,n),m=new Ui(Cp,o.configurationUrl,c),g=Date.now(),{error:h}=await m.getConfiguration();if(h||!m.configuration)throw new Error(`Failed to fetch configuration: ${h}`);let T=new Hi(l.fetch,m.configuration.pciUrl,c),M=new $i(l.fetch,m.configuration.coreUrl,c),x=new Yi(l.fetch,m.configuration.pciUrl,c);x.setOnClientSessionUpdate(E=>{m.configuration=E});let _=new Set;return{get configuration(){return m.configuration},onClientConfigurationUpdate(E){return m.subscribe(E)},checkoutSessionId:n,apiController:l,configurationApi:m,pciApi:T,coreApi:M,clientSessionApi:x,dialogProvider:e,decodedClientToken:o,locale:t||navigator.language||navigator.languages[0]||"en",configurationFetchStartTime:g,translate:a??((E,L)=>L),clientOptions:i,updateClientToken(E){try{let L=Jt(E);m.setDefaultHeader("primer-client-token",L.accessToken),T.setDefaultHeader("primer-client-token",L.accessToken),M.setDefaultHeader("primer-client-token",L.accessToken),x.setDefaultHeader("primer-client-token",L.accessToken)}catch{}},async refreshClientConfiguration(){let{data:E,error:L}=await m.getConfiguration();return L||!E?(C.warn("Failed to refresh client configuration:",L),!1):(m.configuration=E,!0)},subscribeToTeardown(E){return _.add(E),()=>{_.delete(E)}},teardown(){s.remove(),_.forEach(E=>E())}}}var Tp=100;function Pp({height:r,name:t,url:e="",width:a}){let i=new Set,n=window.open(e,t,Ip({height:r,width:a}));if(!n)return;function o(){n?.close(),s()}function s(){i.forEach(l=>l()),i.clear(),window.removeEventListener("beforeunload",o)}return window.addEventListener("beforeunload",o),Np(n).then(s),{close:o,focus(){n.focus()},get isOpen(){return n?.closed===!1},onClose(l){return i.add(l),()=>{i.delete(l)}},setContent(l){n.document.write(l)},setUrl(l){n.location.replace(l)}}}var Np=r=>new Promise(t=>{let e=setInterval(()=>{r.closed&&(clearInterval(e),t())},Tp)});function Ip(r){let t=kp({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:r});return Lp(t)}var kp=({parent:r,popup:t})=>({left:r.left+(r.width-t.width)/2,top:r.top+(r.height-t.height)/2,height:t.height,width:t.width}),Lp=r=>Object.entries(r).map(t=>t.join("=")).join(","),Rp=({name:r,background:t,logoSrc:e,logoAlt:a,message:i})=>`<html>
|
|
36
|
+
`,e.appendChild(i);let n=document.createElement("apple-pay-button"),o=this.clientOptions?.buttonStyle??this.clientOptions?.buttonOptions?.buttonStyle;o&&n.setAttribute("buttonstyle",o);let s=this.clientOptions?.buttonType??this.clientOptions?.buttonOptions?.type??"plain";s&&n.setAttribute("type",s),n.setAttribute("locale",this.context.locale),n.addEventListener("click",this.handleClick.bind(this)),document.body.appendChild(n),setTimeout(()=>{e.appendChild(n)},0)}async handleClick(){if(!this.disabled)try{this.onStartPromise=this.callbacks.onStart(),wt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:O.APPLE_PAY}),this.applePaySession=new ApplePaySession(oo,bu(this.context,this.config)),this.applePaySession.onvalidatemerchant=this.handleValidateMerchant.bind(this),this.applePaySession.onpaymentauthorized=this.handlePaymentAuthorized.bind(this),this.applePaySession.onpaymentmethodselected=this.handlePaymentMethodSelected.bind(this),this.applePaySession.onshippingcontactselected=this.handleShippingContactSelected.bind(this),this.applePaySession.onshippingmethodselected=this.handleShippingMethodSelected.bind(this),this.applePaySession.oncancel=this.handleCancel.bind(this),this.applePaySession.begin()}catch(e){C.errorWithDatadog("Error initiating Apple Pay session",{error:e})}}async handleValidateMerchant(e){if(this.applePaySession)try{let{action:a}=await this.onStartPromise;if(a==="abort")return void this.abort(new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let{data:i,error:n}=await this.context.coreApi.createApplePaySession({validationUrl:e.validationURL,paymentMethodConfigId:this.config.id,merchantDomain:this.context.clientOptions.merchantDomain??window.location.hostname});if(!this.applePaySession)return;if(n||!i)throw n??new G({message:"Failed to validate merchant",code:Q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(a){C.warn("Apple Pay merchant validation failed:",a),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(ki(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling payment method selection",{error:a}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let a=[new ApplePayError("unknown",void 0,this.context.translate(Sa.UNKNOWN_ERROR,ba.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=Ii(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw a=[new ApplePayError("billingContactInvalid","name",this.context.translate(Sa.MISSING_FIRST_OR_LAST_NAME,ba.MISSING_FIRST_OR_LAST_NAME))],new G({message:"Billing contact must include first and last name",code:xt.MISSING_PARAMETER,paymentMethod:O.APPLE_PAY,suggestion:"Ensure Apple Pay requiredBillingContactFields includes name fields"});let{error:l}=await this.context.clientSessionApi.setBillingAddress(s);l&&C.errorWithDatadog("Error setting billing address from Apple Pay",{error:l})}}let i=Ii(e.payment.shippingContact);if(i){let{error:s}=await this.context.clientSessionApi.setShippingAddress(i,e.payment.shippingContact?.phoneNumber,e.payment.shippingContact?.emailAddress);if(s)throw s}let{data:n,error:o}=await this.context.pciApi.postApplePayPaymentInstruments({paymentMethodConfigId:this.config.id,token:e.payment.token});if(o||!n)throw a=[new ApplePayError("unknown",void 0,this.context.translate(Sa.FAILED_TO_TOKENIZE,ba.FAILED_TO_TOKENIZE))],o??new Error("Failed to tokenize Apple Pay payment");this.applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS),this.callbacks.onFinish(n),this.applePaySession=null}catch(i){let n=i instanceof G||i instanceof z?i:new G({message:"Error handling payment authorization",code:F.PAYMENT_FAILED,paymentMethod:O.APPLE_PAY,error:i instanceof Error?i:new Error(String(i))});C.errorWithDatadog("Apple Pay payment authorization failed",{error:n}),this.applePaySession&&(this.applePaySession.completePayment({status:ApplePaySession.STATUS_FAILURE,errors:a}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:a,error:i}=await this.context.clientSessionApi.setShippingAddress(Ii(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!a||i)throw i??new G({message:"Failed to set shipping address",code:Q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY});this.applePaySession.completeShippingContactSelection(ki(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling shipping contact selection",{error:a}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let a=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&a){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new G({message:"Failed to select shipping method",code:Q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(ki(this.context,this.config))}catch(i){C.errorWithDatadog("Error handling shipping method selection",{error:i}),this.abort();return}}handleCancel(){this.applePaySession=null,this.context.clientSessionApi.unselectPaymentMethod(),C.info("Apple Pay payment was cancelled by the user")}abort(e){this.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onFinish(void 0,e??new Error("Apple Pay payment aborted"))}},sr=class extends gt{constructor(){super(...arguments);k(this,"blikCode","")}setBlikCode(e){this.blikCode=e}getBlikCode(){return this.blikCode}clearBlikCode(){this.blikCode=""}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new z({message:"BLIK code must be exactly 6 digits",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e={type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Uo()?"MOBILE_WEB":"WEB",browserInfo:Qi(),blikCode:this.blikCode}};try{let{error:a,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),a||!i)throw a??new z({message:"Unable to tokenize BLIK payment method",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(a){throw this.clearBlikCode(),a}}async createPayment(e){let a=await super.createPayment(e),i=a.requiredAction?.clientToken;if(!i)throw new Ge({message:"No client token provided for BLIK payment",code:no.MISSING_CLIENT_TOKEN,response:{id:a.id,data:a}});let n=Jt(i);if(!this.isValidBlikClientToken(n))throw new Ge({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:no.INVALID_CLIENT_TOKEN,response:{id:a.id,data:a}});let{promise:o,abort:s}=this.pollStatus(n.statusUrl),l=await o;if(s(),"error"in l)throw l.error;let c=l.id;if(!c){let m=await this.context.pciApi.getResumeStatus(n.statusUrl);if(m.error||!m.data?.id)throw m.error??new Error("Unable to get resume token");c=m.data.id}return await this.resumePayment(a.id,c)}pollStatus(e){let a=!0,i=1e3,n=864e5,o=Date.now();return{promise:new Promise(async s=>{for(;a;){if(Date.now()-o>=n)return void s({error:new Error("BLIK payment polling timed out after 24 hours")});let{data:l,error:c}=await this.context.pciApi.getResumeStatus(e);if(c)return void s({error:c instanceof Error?c:new Error(String(c))});if(l?.status==="COMPLETE")return void s({id:l.id});await qt(i)}}),abort:()=>{a=!1}}}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let a=e;return!(a.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in a)||typeof a.statusUrl!="string"||!a.statusUrl)}},Wo="https://sdk.primer.io/web/hosted-pages/v0.0.24",Fi=!1,Cu=`${Wo}/api-controller.html`,Mu=`${Wo}/hosted-input.html`,Eu="https://goat-assets.production.core.primer.io";function Zo(r,t,e){let a={checkoutSessionId:r,name:t};e!==void 0&&(a.defaultValue=e);try{return btoa(JSON.stringify(a))}catch{let{defaultValue:n,...o}=a;return btoa(JSON.stringify(o))}}ji("../../node_modules/card-validator/dist/index.js");var ue={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},lo="cardSecurityCodeRecapture";Object.values(ue);function Tu({networks:r,source:t},e){let a=e,i=new Set(a.map(m=>ur(m).backend)),n=r.map(m=>({...m,allowed:i.has(m.network)})).sort((m,g)=>m.allowed?a.indexOf(m.network)-a.indexOf(g.network):1),o=n.filter(m=>m.allowed),s=t==="REMOTE"&&o.length>1,[l,...c]=n;return{cardNetworkChangeEventData:{detectedCardNetworks:{items:n.map(Qa),preferred:o.length?Qa(o[0]):void 0},...s&&{selectableCardNetworks:{items:o.map(Qa),preferred:o.length?Qa(o[0]):void 0}},source:t},binDataAvailableEventData:{preferred:l,alternatives:c,status:t==="REMOTE"?"complete":"partial"}}}function Qa({network:r,displayName:t,allowed:e}){return{network:r,displayName:t,allowed:e}}function Jo(r,t){return{cardNumber:va(r,ue.cardNumber),cardSecurityCode:va(r,ue.cardSecurityCode),cardExpiryDate:va(r,ue.cardExpiryDate),cardholderName:va(r,ue.cardholderName,t?.cardholderName)}}function va(r,t,e){let a=document.createElement("iframe"),i=Zo(r,t,e);return a.src=`${Mu}#${i}`,a.setAttribute("tabindex","0"),a.setAttribute("frameBorder","0"),a.style.border="none",a.style.boxSizing="border-box",a.style.height="20px",a.style.width="100%",a.style.colorScheme="auto",a}var lr=class extends gt{constructor(e,a){super(e,a);k(this,"iframes");this.iframes=Jo(a.checkoutSessionId)}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:a}=await this.context.pciApi.postCardPaymentInstruments();if(e||!a)throw e??new z({code:F.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:O.PAYMENT_CARD});return a}};function Pu(r){if(!r)return{};let t=r.indexOf(" ");return t===-1?{firstName:r}:{firstName:r.substring(0,t),lastName:r.substring(t+1)}}function Li(r){let{firstName:t,lastName:e}=Pu(r.name);return{firstName:t||null,lastName:e||null,addressLine1:r.address1||null,addressLine2:r.address2||null,city:r.locality||null,state:r.administrativeArea||null,postalCode:r.postalCode||null,countryCode:r.countryCode||null}}function co(r){return r.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var uo=2,po=0,Nu="https://pay.google.com/gp/p/js/pay.js",Iu={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},mo=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],Xa={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},er={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},ku="buy",Lu="black",Ru="fill",dr=class extends gt{constructor(){super(...arguments);k(this,"disabled",!1);k(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,a){return this.context.translate?.(e,a)??a}async tokenize(){throw new z({code:F.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:O.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await Ho(Nu),!0}catch{return C.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:a}=this.context.configuration.clientSession.order;if(!e)throw new G({code:xt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:O.GOOGLE_PAY});if(!a)throw new G({code:xt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:O.GOOGLE_PAY});if(!await this.loadGooglePayScript())return C.error("Google Pay script failed to load"),!1;let n=this.context.configuration.env==="PRODUCTION"?"PRODUCTION":"TEST";this.client=new google.payments.api.PaymentsClient({environment:n,...this.needsPaymentDataCallbacks()&&{paymentDataCallbacks:{onPaymentDataChanged:s=>this.handlePaymentDataChanged(s)}}});try{let{result:s,paymentMethodPresent:l}=await this.client.isReadyToPay(this.buildIsReadyToPayRequest());if(!s)return C.info("Google Pay is not available in this browser/device"),!1;if(this.clientOptions?.existingPaymentMethodRequired&&l===!1)return C.info("Google Pay: existingPaymentMethodRequired is true but no existing payment method is available"),!1}catch(s){return C.error("Google Pay isReadyToPay check failed",{error:s}),!1}let o=this.context.onClientConfigurationUpdate(s=>{let l=s.clientSession?.order;(!l||!l.totalOrderAmount||!l.currencyCode)&&C.warn("Google Pay: Order details are missing or incomplete after client session update. Ensure order details (totalOrderAmount, currencyCode, countryCode) are always provided.")});return this.context.subscribeToTeardown(o),!0}needsPaymentDataCallbacks(){return!!(this.clientOptions?.requireShippingMethod||this.shouldCaptureShippingAddress)}buildIsReadyToPayRequest(){return{apiVersion:uo,apiVersionMinor:po,allowedPaymentMethods:[this.allowedPaymentMethod],existingPaymentMethodRequired:this.clientOptions?.existingPaymentMethodRequired}}async render(e){if(!this.client)return void C.error("Google Pay client not initialized. Call setup() first.");let a=this.client.createButton({buttonType:this.clientOptions?.buttonType??ku,buttonColor:this.clientOptions?.buttonColor??Lu,buttonSizeMode:this.clientOptions?.buttonSizeMode??Ru,buttonRadius:this.clientOptions?.buttonRadius,buttonLocale:this.clientOptions?.buttonLocale,buttonBorderType:this.clientOptions?.buttonBorderType,onClick:i=>this.handleClick(i),buttonRootNode:e instanceof ShadowRoot?e:void 0});e.appendChild(a)}async handleClick(e){if(!this.client)return void C.error("Google Pay client not available");let a=this.callbacks.onStart();wt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:O.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await a;if(n==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});await this.processPaymentData(i)}catch(i){if(i.statusCode==="CANCELED")return void this.context.clientSessionApi.unselectPaymentMethod();C.errorWithDatadog("Google Pay error",{error:i}),this.callbacks.onFinish(void 0,i)}}get clientOptions(){return this.context.clientOptions.googlePay}get shouldCaptureShippingAddress(){return!!(this.clientOptions?.captureShippingAddress||this.clientOptions?.shippingAddressParameters)}async processPaymentData(e){if(this.clientOptions?.captureBillingAddress&&await this.updateBillingAddress(e),(this.shouldCaptureShippingAddress||this.clientOptions?.requireShippingMethod||this.clientOptions?.emailRequired)&&await this.updateShippingDetails(e),this.clientOptions?.requireShippingMethod){let n=e.shippingOptionData?.id;n&&await this.context.clientSessionApi.selectShippingMethod(n)}let{data:a,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:rr.encode(e.paymentMethodData.tokenizationData.token)});if(i||!a)throw this.callbacks.onFinish(void 0,i),i??new z({code:F.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:O.GOOGLE_PAY});this.callbacks.onFinish(a)}async updateBillingAddress(e){let a=e.paymentMethodData.info?.billingAddress;if(a){let i=Li(a);await this.context.clientSessionApi.setBillingAddress(i)}else C.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let a=e.shippingAddress,i=e.email,n=a?.phoneNumber;if(a||n||i){let o=a?Li(a):void 0;await this.context.clientSessionApi.setShippingAddress(o,n,i)}else C.warn("Google Pay: No shipping address, phone number, or email found in payment data")}async handlePaymentDataChanged(e){let a=e.callbackTrigger;try{if(a==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(a==="SHIPPING_ADDRESS"||a==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=Li(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:co(o),defaultSelectedOptionId:n?.selectedShippingMethod||o[0]?.id}},newTransactionInfo:this.getCurrentTransactionInfo()}}return{newTransactionInfo:this.getCurrentTransactionInfo()}}catch(i){return C.errorWithDatadog("Google Pay: Error handling payment data change",{error:i}),{error:{reason:"OTHER_ERROR",message:"An error occurred while processing your request",intent:a==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:a,totalOrderAmount:i}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:a,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:ya(i,a),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:a,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(Xa.SUBTOTAL,er.SUBTOTAL),type:"SUBTOTAL",price:ya(i,a)}),c):(n&&n.length>0&&n.forEach(m=>{c.push({label:m.description||this.translate(Xa.ITEM,er.ITEM),type:"LINE_ITEM",price:ya(m.amount,a)})}),o&&o.length>0&&o.filter(m=>m.amount!==0).forEach(m=>{c.push({label:m.type||m.description||this.translate(Xa.FEE,er.FEE),type:"LINE_ITEM",price:ya(m.amount,a)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(Xa.SHIPPING,er.SHIPPING),type:"LINE_ITEM",price:ya(s.amount,a)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return mo;let a=e.map(i=>Iu[i]).filter(i=>!!i);return a.length>0?a:mo}get allowedPaymentMethod(){let e=this.clientOptions?.captureBillingAddress;return{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.allowedCardNetworks,...e&&{billingAddressRequired:!0,billingAddressParameters:{format:"FULL"}}}}}buildPaymentDataRequest(){let e=this.clientOptions?.shippingAddressParameters,a=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:uo,apiVersionMinor:po,...a&&{emailRequired:!0},...(this.shouldCaptureShippingAddress||i)&&{shippingAddressRequired:!0,...e&&{shippingAddressParameters:{...e.allowedCountryCodes&&{allowedCountryCodes:e.allowedCountryCodes},...e.phoneNumberRequired&&{phoneNumberRequired:!0}}}},...i&&{shippingOptionRequired:!0,...o&&o.length>0&&{shippingOptionParameters:{shippingOptions:co(o),defaultSelectedOptionId:s||o[0]?.id}}},...this.needsPaymentDataCallbacks()&&{callbackIntents:[...i?["SHIPPING_ADDRESS","SHIPPING_OPTION"]:["SHIPPING_ADDRESS"]]},transactionInfo:this.getCurrentTransactionInfo(),merchantInfo:{merchantId:this.config.options.merchantId,merchantName:this.config.options.merchantName},allowedPaymentMethods:[{...this.allowedPaymentMethod,tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"primer",gatewayMerchantId:this.config.options.merchantId}}}]}}};function _u(r,t){var e={};for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&t.indexOf(a)<0&&(e[a]=r[a]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,a=Object.getOwnPropertySymbols(r);i<a.length;i++)t.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(r,a[i])&&(e[a[i]]=r[a[i]]);return e}function xu(r,t){var e=document.querySelector('script[src="'.concat(r,'"]'));if(e===null)return null;var a=qo(r,t),i=e.cloneNode();if(delete i.dataset.uidAuto,Object.keys(i.dataset).length!==Object.keys(a.dataset).length)return null;var n=!0;return Object.keys(i.dataset).forEach(function(o){i.dataset[o]!==a.dataset[o]&&(n=!1)}),n?e:null}function wu(r){var t=r.url,e=r.attributes,a=r.onSuccess,i=r.onError,n=qo(t,e);n.onerror=i,n.onload=a,document.head.insertBefore(n,document.head.firstElementChild)}function Du(r){var t=r.sdkBaseUrl,e=r.environment,a=_u(r,["sdkBaseUrl","environment"]),i=t||Gu(e),n=a,o=Object.keys(n).filter(function(c){return n[c]!==void 0&&n[c]!==null&&n[c]!==""}).reduce(function(c,m){var g=n[m].toString();return m=Ou(m),m.substring(0,4)==="data"||m==="crossorigin"?c.attributes[m]=g:c.queryParams[m]=g,c},{queryParams:{},attributes:{}}),s=o.queryParams,l=o.attributes;return s["merchant-id"]&&s["merchant-id"].indexOf(",")!==-1&&(l["data-merchant-id"]=s["merchant-id"],s["merchant-id"]="*"),{url:"".concat(i,"?").concat(Bu(s)),attributes:l}}function Ou(r){var t=function(e,a){return(a?"-":"")+e.toLowerCase()};return r.replace(/[A-Z]+(?![a-z])|[A-Z]/g,t)}function Bu(r){var t="";return Object.keys(r).forEach(function(e){t.length!==0&&(t+="&"),t+=e+"="+r[e]}),t}function Gu(r){return r==="sandbox"?"https://www.sandbox.paypal.com/sdk/js":"https://www.paypal.com/sdk/js"}function qo(r,t){t===void 0&&(t={});var e=document.createElement("script");return e.src=r,Object.keys(t).forEach(function(a){e.setAttribute(a,t[a]),a==="data-csp-nonce"&&e.setAttribute("nonce",t["data-csp-nonce"])}),e}function Ku(r,t){if(t===void 0&&(t=Promise),Qo(r,t),typeof document>"u")return t.resolve(null);var e=Du(r),a=e.url,i=e.attributes,n=i["data-namespace"]||"paypal",o=ho(n);return i["data-js-sdk-library"]||(i["data-js-sdk-library"]="paypal-js"),xu(a,i)&&o?t.resolve(o):Fu({url:a,attributes:i},t).then(function(){var s=ho(n);if(s)return s;throw new Error("The window.".concat(n," global variable is not available."))})}function Fu(r,t){t===void 0&&(t=Promise),Qo(r,t);var e=r.url,a=r.attributes;if(typeof e!="string"||e.length===0)throw new Error("Invalid url.");if(a!==void 0&&typeof a!="object")throw new Error("Expected attributes to be an object.");return new t(function(i,n){if(typeof document>"u")return i();wu({url:e,attributes:a,onSuccess:function(){return i()},onError:function(){var o=new Error('The script "'.concat(e,'" failed to load. Check the HTTP status code and response body in DevTools to learn more.'));return n(o)}})})}function ho(r){return window[r]}function Qo(r,t){if(typeof r!="object"||r===null)throw new Error("Expected an options object.");var e=r.environment;if(e&&e!=="production"&&e!=="sandbox")throw new Error('The `environment` option must be either "production" or "sandbox".');if(t!==void 0&&typeof t!="function")throw new Error("Expected PromisePonyfill to be a function.")}var tr=new Map,go={getOrCreateNamespace(r){let t=tr.get(r);return t?t.namespace:Pe()},getInstance(r){return tr.get(r)?.instance??null},storeInstance(r,t,e){tr.set(r,{instance:t,namespace:e})},hasInstance(r){return tr.has(r)}};async function Vu({context:r,configId:t,paymentMethodType:e,callbacks:a}){try{let{action:i}=await a.onStart();if(i==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e});let{data:n,error:o}=await r.coreApi.createPaypalBillingAgreement({paymentMethodConfigId:t});if(o||!n){let s=o?.message??"Failed to create billing agreement";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.tokenId}catch(i){throw C.errorWithDatadog("PayPal billing agreement creation failed:",{error:i}),a.onFinish(void 0,i),i instanceof G||i instanceof z?i:new G({message:"Failed to create billing agreement",code:F.PAYMENT_FAILED,paymentMethod:e})}}async function Uu({context:r,configId:t,paymentMethodType:e,callbacks:a,data:i}){try{let n=i.billingToken;if(!n)throw new z({message:"Billing token not provided",code:F.TOKENIZATION_ERROR,paymentMethod:e});let{data:o,error:s}=await r.coreApi.confirmPaypalBillingAgreement({paymentMethodConfigId:t,tokenId:n});if(s||!o){let h=s?.message??"Failed to confirm billing agreement";throw new z({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}let l=o,c={paypalBillingAgreementId:l.billingAgreementId,shippingAddress:l.shippingAddress,externalPayerInfo:l.externalPayerInfo},{error:m,data:g}=await r.pciApi.postPaypalPaymentInstruments(c,{tokenType:"MULTI_USE",paymentFlow:"VAULT"});if(m||!g){let h=m?.message??"Unable to vault PayPal payment method";throw new z({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}a.onFinish(g)}catch(n){throw C.errorWithDatadog("PayPal billing agreement approval failed:",{error:n}),a.onFinish(void 0,n),n instanceof z||n instanceof G?n:new z({message:"Failed to approve billing agreement",code:F.TOKENIZATION_ERROR,paymentMethod:e})}}var Hu="gold",Yu="black",$u="rect",zu="paypal",ju="vertical",Xo="horizontal",yo=2,fo=["paypal","paylater"],es={default:{color:Hu},card:{validColors:["black","white"],defaultColor:Yu}};function Wu(r){if(!r)return;let t=es[r];if(t&&"validColors"in t)return t}function Zu(r,t){let e=Wu(t);if(!e)return r??es.default.color;let a=r??e.defaultColor;return e.validColors.includes(a)?a:(C.warn(`PayPal: Invalid color "${a}" for ${t} button. Only supports: ${e.validColors.join(", ")}. Falling back to "${e.defaultColor}".`),e.defaultColor)}var Ju=25,qu=55;function Qu(r){return parseFloat(r)||0}function Xu(r){let t=Qu(r);return Math.max(Ju,Math.min(qu,t))}function ep(r,t,e){let a=t?r?.[t]:void 0,i=a?.tagline??r?.tagline??!1,n=i?Xo:ju,o,s=a?.height??r?.height;s!=null?o=s:e!=null&&(o=Xu(String(e)));let l=a?.borderRadius??r?.borderRadius,c=a?.disableMaxWidth??r?.disableMaxWidth,m=a?.color??r?.color;return{color:Zu(m,t),shape:a?.shape??r?.shape??$u,label:a?.label??r?.label??zu,layout:a?.layout??r?.layout??n,tagline:i,...o!=null&&{height:o},...l!=null&&{borderRadius:l},...c!=null&&{disableMaxWidth:c}}}function tp(r,t,e,a){let i={style:r,onInit:e.onInit,onClick:e.onClick,onCancel:e.onCancel,onError:e.onError};return t&&a?(i.createBillingAgreement=a.createBillingAgreement,i.onApprove=a.onApprove):i.onApprove=e.onApprove,i}function ap(r){if(!r)return;let t={first_name:r.firstName,last_name:r.lastName,address_line_1:r.addressLine1??"",address_line_2:r.addressLine2,city:r.city??"",state:r.state,postal_code:r.postalCode??"",country_code:r.countryCode??""},{address_line_1:e,city:a,postal_code:i,country_code:n}=t;if(!(!e||!a||!i||!n))return t}function rp(r){if(!r)return null;let t=r.purchase_units?.[0]?.shipping;if(!t?.address)return null;let e=t.address,a=t.name;return{firstName:a?.given_name,lastName:a?.surname,addressLine1:e.address_line_1,addressLine2:e.address_line_2,city:e.admin_area_2,state:e.admin_area_1,postalCode:e.postal_code,countryCode:e.country_code}}function ip(r,t,e){let{order:{currencyCode:a,merchantAmount:i,totalOrderAmount:n,shipping:o,lineItems:s=[],fees:l=[]},customer:c}=r;if(!a)throw new G({message:"Currency code is not provided",code:xt.MISSING_PARAMETER,paymentMethod:e});let m={amount:i??n,currencyCode:a,paymentMethodConfigId:t,amountBreakdown:{}},g=c?.shippingAddress,h=ap(g);h&&(m.shipping_address=h);let T=!s.some(M=>!M.name&&!M.description);if(T&&(m.items=s.map(M=>{let{name:x,description:_,taxAmount:E,amount:L,quantity:K}=M,j=E?Math.floor(E/K):0;return{name:_||x||"",unit_amount:{value:L,currency_code:a},quantity:K.toString(),tax:{value:j,currency_code:a}}})),T&&s.length){let M=s.reduce((ce,{amount:V,quantity:Be})=>ce+V*Be,0),x=l?.reduce?.((ce,{amount:V})=>ce+(V??0),0),_=s?.reduce((ce,{discountAmount:V})=>ce+(V??0),0),E=s?.reduce((ce,{taxAmount:V})=>ce+(V??0),0),L=o?.amount??0,K=x??0,j=M+E+L+K-_;m.amountBreakdown={item_total:{value:M,currency_code:a},tax_total:{value:E,currency_code:a},handling:{value:K,currency_code:a},shipping:{value:L,currency_code:a},discount:{value:_,currency_code:a}},m.amount=j}return m}async function np({context:r,configId:t,paymentMethodType:e,callbacks:a,skipOnStartCallback:i=!1}){try{if(!i){let{action:s}=await a.onStart();if(s==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e})}let{data:n,error:o}=await r.coreApi.createPaypalOrder(ip(r.configuration.clientSession,t,e));if(o||!n){let s=o?.message??"Unable to create PayPal order";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.orderId}catch(n){throw a.onFinish(void 0,n),n}}async function op({context:r,paymentMethodType:t,callbacks:e,data:a,actions:i,deferredOnStartCallback:n=!1}){if(n){let{action:g}=await e.onStart();if(g==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:t})}let o=null;try{o=await i?.order?.get()??null}catch(g){C.warn("Failed to get PayPal order details",g)}let s=rp(o),l={external_payer_info:{email:o?.payer?.email_address,external_payer_id:a.payerID??void 0,first_name:o?.payer?.name?.given_name,last_name:o?.payer?.name?.surname},paypal_order_id:a.orderID,paypal_status:o?.status};s&&(l.shipping_address=s);let{error:c,data:m}=await r.pciApi.postPaypalPaymentInstruments(l);if(c||!m){let g=c?.message??"Unable to create payment instrument";throw new z({message:g,code:F.TOKENIZATION_ERROR,paymentMethod:t})}e.onFinish(m)}var sp=["buttons","funding-eligibility"],vo=[],So="paypal";function ts(r){if(!r?.length)return;r.includes(So)&&C.warn("PayPal: Cannot disable paypal funding source");let t=r.filter(e=>e!==So);return t.length>0?t:void 0}var lp="authorize";function dp(r,t,e){return(r??t==="PREFER_VAULT")&&e}function bo({isVaultFlow:r,configIntent:t}){return r?"tokenize":t??lp}function cp(r,t,e,a){let{clientId:i,intent:n}=t.options,o=r.configuration.clientSession.order.currencyCode,s=r.clientOptions.paypal?.disableFunding??(vo.length>0?vo:void 0),l=ts(s),c=r.clientOptions?.paypal?.enableFunding,m={dataNamespace:e,clientId:i,currency:o,components:sp,...l&&l.length>0?{disableFunding:l}:{},...c&&c.length>0?{enableFunding:c}:{},integrationDate:r.clientOptions.paypal?.integrationDate,debug:r.clientOptions.paypal?.debug};return(Fi||r.decodedClientToken.env==="SANDBOX"||r.decodedClientToken.env==="STAGING")&&(m.buyerCountry=r.clientOptions?.paypal?.buyerCountry),a?(m.vault="true",m.intent=bo({isVaultFlow:!0,configIntent:n})):(m.vault="false",m.intent=bo({isVaultFlow:!1,configIntent:n})),m}var cr=class extends gt{constructor(e,a){super(e,a);k(this,"paypalInstance");k(this,"dataNamespace");k(this,"isVaultFlow",!1);k(this,"isSetupComplete",!1);k(this,"setupPromise");k(this,"eligibleFundingSources",[]);k(this,"currentFundingSource",null);k(this,"onStartDeferred",!1);k(this,"disabled",!1);this.dataNamespace=go.getOrCreateNamespace(e.id),this.context.onClientConfigurationUpdate(async()=>{C.info("PayPal: Client session updated, refreshing PayPal buttons");try{await this.setup()}catch(i){C.warn("PayPal: Failed to refresh on client session update:",i)}})}async setDisabled(e){this.disabled=e}async tokenize(){throw new z({message:"PayPal does not support direct tokenization",code:F.TOKENIZATION_ERROR,paymentMethod:O.PAYPAL})}async setup(){let{clientId:e}=this.config.options;return this.setupPromise?(C.info("PayPal setup already in progress, waiting..."),this.setupPromise):this.isSetupComplete&&this.paypalInstance?.Buttons?(C.info("PayPal setup already completed, skipping"),!0):e?(this.setupPromise=(async()=>{try{let a=this.context.clientOptions.paypal?.vault,i=this.context.clientOptions.paypal?.paymentFlow,n=this.context.configuration.clientSession.paymentMethod?.vaultOnSuccess??!1;this.isVaultFlow=dp(a,i,n);let o=cp(this.context,this.config,this.dataNamespace,this.isVaultFlow);C.debug("%c PAYPAL %c Script Configuration ","background: #0070BA; color: #ffffff; font-weight: bold; padding: 4px 12px; border-radius: 3px 0 0 3px; font-size: 14px;","background: #003087; color: #ffffff; padding: 4px 12px; border-radius: 0 3px 3px 0; font-size: 14px;",o);let s=await Ku(o);if(!s)return C.warn("Failed to load PayPal SDK"),!1;this.paypalInstance=s,go.storeInstance(this.config.id,s,this.dataNamespace);let l=this.context.clientOptions.paypal?.enableFunding,c=ts(this.context.clientOptions.paypal?.disableFunding),g=(s.getFundingSources?.()??[]).filter(h=>s?.isFundingEligible?.(h));return C.debug("PayPal: Eligible funding sources from PayPal SDK:",g),this.eligibleFundingSources=this.filterFundingSources(g,l,c),(l?.length||c?.length)&&(C.debug("PayPal: Primer SDK options:",{enableFunding:l??[],disableFunding:c??[]}),C.debug("PayPal: Funding sources after Primer SDK filter:",this.eligibleFundingSources)),this.eligibleFundingSources.length===0?(C.warn("PayPal: No funding sources are eligible with current configuration"),!1):!0}catch(a){return C.warn("PayPal setup failed:",{error:a}),this.setupPromise=void 0,!1}})(),this.setupPromise):(C.warn("PayPal clientId is required"),!1)}async render(e,a){let{Buttons:i}=this.paypalInstance;if(!i)throw new G({message:"PayPal Buttons component not available",code:xt.INVALID_USAGE,paymentMethod:O.PAYPAL});let n=this.context.clientOptions.paypal?.style,o=a?.style?.buttonHeight,s=n?.layout===Xo,l={onInit:this.handleInit.bind(this),onClick:this.handleClick.bind(this),onApprove:this.handleApprove.bind(this),onCancel:this.handleCancel.bind(this),onError:this.handleError.bind(this)},c=this.isVaultFlow?{createBillingAgreement:()=>Vu({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks}),onApprove:M=>Uu({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,data:M})}:void 0,m=this.eligibleFundingSources,g=[];for(let M of m){let x=ep(n,M,o),_=tp(x,this.isVaultFlow,l,c);this.isVaultFlow||(_.createOrder=this.handleCreateOrder.bind(this));let E=i({..._,fundingSource:M});E.isEligible()?g.push({button:E,fundingSource:M}):C.debug(`PayPal: Button for "${M}" is not eligible with current config`)}if(g.length===0)throw C.warn("PayPal: No buttons were eligible to render with current configuration"),new G({message:"No PayPal buttons eligible to render",code:xt.INVALID_USAGE,paymentMethod:O.PAYPAL});let h=s&&g.length>yo?this.selectButtonsForHorizontalLayout(g):g;s&&this.applyHorizontalLayoutStyles(e,h.length);let T=h.map(({button:M})=>M.render(e));await Promise.all(T)}selectButtonsForHorizontalLayout(e){let a=new Set(fo),i=fo.map(o=>e.find(s=>s.fundingSource===o)).filter(o=>o!==void 0),n=e.filter(o=>!a.has(o.fundingSource));return[...i,...n].slice(0,yo)}applyHorizontalLayoutStyles(e,a){e.style.display="grid",e.style.gridTemplateColumns=`repeat(${a}, 1fr)`,e.style.gap="10px"}handleInit(e,a){let{clientSession:i}=this.context.configuration,n=!!i.order.currencyCode,o=!!i.order.totalOrderAmount||!!i.order.merchantAmount;if(!n||!o){C.warn("PayPal button disabled: missing currency or amount"),a.disable();return}a.enable()}handleClick(e,a){return this.currentFundingSource=e.fundingSource??null,wt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYPAL"}),a.resolve()}async handleCreateOrder(){let e=this.currentFundingSource==="card";return this.onStartDeferred=e,np({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,skipOnStartCallback:e})}async handleApprove(e,a){let i=this.onStartDeferred;return this.onStartDeferred=!1,op({context:this.context,paymentMethodType:this.config.type,callbacks:this.callbacks,data:e,actions:a,deferredOnStartCallback:i})}handleCancel(){this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,new G({message:"The PayPal payment was cancelled by the user.",paymentMethod:O.PAYPAL}))}handleError(e){C.errorWithDatadog("PayPal error:",e),this.callbacks.onFinish(void 0,e)}filterFundingSources(e,a,i){return e.filter(n=>!(a?.length&&!a.includes(n)||i?.includes(n)))}};function Ao(r,t,e){if(!r)return null;let a={id:r.id,orderId:r.orderId};return t?.paymentInstrumentData&&e&&(a.paymentMethodData={paymentMethodType:e,...t.paymentInstrumentData}),a}var as=(r,t,e,a,i)=>{let n=e;if(t?.status==="FAILED"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.checkoutOutcome==="CHECKOUT_FAILURE"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="PENDING"&&!t.requiredAction?.clientToken&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" ended up in a "PENDING" state without any required action. The SDK does not know how to handle this state. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="SUCCESS"&&t.checkoutOutcome!=="CHECKOUT_FAILURE"||t?.status==="PENDING"&&t.showSuccessCheckoutOnPendingPayment||t?.checkoutOutcome==="CHECKOUT_COMPLETE")return void r.onCheckoutComplete?.({payment:Ao(t,a,i)});r.onCheckoutFail?.(n||new G({code:F.PAYMENT_FAILED,message:`The payment${t?.id?` "${t.id}"`:""} is in an inconsistent state without any required action. The SDK does not know how to handle this state. Please contact Primer.`}),{payment:Ao(t,a,i)??void 0})},up=async(r,t)=>{let e=t.config.type;if(!r.onBeforePaymentCreate)return{action:"continue"};let a=setTimeout(()=>{C.warn("onBeforePaymentCreate did not resolve within 10 seconds. Primer SDK will remain in a loading state until `continuePaymentCreation` or `abortPaymentCreation` is called.")},1e4);return new Promise(i=>{r.onBeforePaymentCreate({paymentMethodType:e},{continuePaymentCreation:n=>{clearTimeout(a),C.log(`Continuing payment creation for ${e}`),n?.idempotencyKey&&t.setIdempotencyKey(n.idempotencyKey),r.onPaymentCreationStart?.(),i({action:"continue"})},abortPaymentCreation:()=>{clearTimeout(a),C.log(`Aborting payment creation for ${e}`),i({action:"abort"})}})})};async function Ca(r,t,e){if(t.setCallbacks({onStart:()=>(t.context.clientSessionApi.selectPaymentMethod(t.config.type),wt({eventName:"PAYMENT_PROCESSING_STARTED",paymentMethod:t.config.type}),up(r,t)),onFinish:(a,i)=>{Co(r,t,a,i)}}),!e)return t.start();{let a,i;try{i=await t.tokenizeVaulted(e.id)}catch(n){a=n}return Co(r,t,i,a)}}async function Co(r,t,e,a){let i;if(e&&!a)try{if(i=await t.createPayment(e),i.cancelled)return;i.status!=="FAILED"&&(i=await t.handleRequiredAction(i))}catch(n){a=n}as(r,i,a,e,t.config.type)}var Mo=Symbol("PROXY_MARKER");function Xi({namespace:r,onMessage:t,sendMessage:e}){function a(i,n){return new Proxy(i,{get(o,s,l){if(s==="then")return null;if(o[Mo])return Reflect.get(o,s,l);let c=()=>{};return c[Mo]=!0,a(c,[...n,s])},apply(o,s,l){return new Promise(async(c,m)=>{try{let g=[],h=l.map(_=>{if(typeof _!="function")return _;{let E=Pe();return g.push(E),t(L=>{L.namespace===r&&L.sender===_i.PROVIDER&&L.type===Ri.CALLBACK&&L.id===E&&_(...L.data)}),E}}),T=Pe(),M=t(_=>{_.namespace===r&&_.sender===_i.PROVIDER&&_.type===Ri.APPLY&&_.id===T&&(_.error?m(new Error(_.error)):c(_.data),M?.())}),x={type:Ri.APPLY,sender:_i.INJECTOR,id:T,path:n,args:h,callbackIds:g,timeStamp:Date.now(),namespace:r};e(x)}catch(g){m(g)}})}})}return a({},[])}var Ri={APPLY:"apply",CALLBACK:"callback"},_i={PROVIDER:"provider",INJECTOR:"injector"};function Vi(r,t){let e=t?.input?.base?.height;e&&(r.style.height=typeof e=="number"?`${e}px`:e)}function pp(r,t,e,a={}){let i=r.cardholderName?.defaultValue??r.card?.cardholderName?.defaultValue,n=Jo(t.checkoutSessionId,{cardholderName:i});e.iframes=n;let o=[],s="LOCAL",l={[ue.cardNumber]:void 0,[ue.cardExpiryDate]:void 0,[ue.cardSecurityCode]:void 0,[ue.cardholderName]:void 0},c=!1;t.subscribeToTeardown(()=>{c=!0});let m={createHostedInputs:()=>{let g=h=>{let T=new Map;return{getOptions:()=>{},setOptions:M=>{Vi(e.iframes[h],M.style),e.iframes[h].setAttribute("title",M.ariaLabel||""),l[h]?.setOptions(M)},render:(M,x)=>{let _=e.iframes[h];if(!_)return C.errorWithDatadog(`No iframe found for ${h}`),Promise.resolve();let E;return E=typeof M=="string"?document.getElementById(M):M,E?(Vi(_,x.style),E.appendChild(_),new Promise(L=>{_.onload=()=>{if(c){C.warn(`Teardown was already called, aborting render for ${h}`),_.remove(),L();return}l[h]=Xi({namespace:`${t.checkoutSessionId}-${h}`,onMessage:V=>{let Be=ga=>V(ga.data);return window.addEventListener("message",Be),()=>window.removeEventListener("message",Be)},sendMessage:V=>{_.contentWindow.postMessage(V,"*")}}),e.iframes[h].setAttribute("title",x.ariaLabel||"");let K=r.cardholderName??r.card?.cardholderName,{defaultValue:j,...ce}=K??{};l[h].setOptions({...x,orderedAllowedCardNetworks:t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks,cardholderName:ce}),l[h].setBinDataLoadingChange(V=>{V&&a.onCardNetworksLoading?.(),a.onBinDataLoadingChange?.(V)}),l[h].setOnBlur(()=>{try{T.get("blur")?.()}catch(V){C.errorWithDatadog(`Blur listener error for ${h}`,{error:V})}}),l[h].setOnFocus(()=>{try{T.get("focus")?.()}catch(V){C.errorWithDatadog(`Focus listener error for ${h}`,{error:V})}}),l[h].setOnInput(V=>{let Be={...V,errorCode:V.error,active:V.focused};try{T.get("input")?.(Be),T.get("change")?.(Be)}catch(ga){C.errorWithDatadog(`Input listener error for ${h}`,{error:ga})}}),l[h].setOnEnter(()=>{try{T.get("enter")?.()}catch(V){C.errorWithDatadog(`Enter listener error for ${h}`,{error:V})}}),h===ue.cardNumber&&(l[h].setBinDataApiConfig(t.configuration.binDataUrl,t.decodedClientToken.accessToken),l[h].setOnCardNetworksChange((V,Be,ga)=>{if(Be!==s||mp(o,V)){o=V,s=Be;let{cardNetworkChangeEventData:kc,binDataAvailableEventData:Lc}=Tu({networks:o,source:s},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks);a.onCardNetworksChange?.(kc),a.onBinDataAvailable?.({...Lc,firstDigits:ga})}}))},L()})):(C.error(`Container not found for ${h}:`,M),Promise.resolve())},addEventListener:(M,x)=>{T.set(M,x)},focus:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.focus()}catch(x){C.errorWithDatadog(`Focus send error for ${h}`,{error:x})}else C.warn(`Focus failed for ${h} - iframe not available`)},blur:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.blur()}catch(x){C.errorWithDatadog(`Blur send error for ${h}`,{error:x})}},setDisabled:M=>{l[h]?.setDisabled(M)}}};return{cardNumberInput:g(ue.cardNumber),cardholderNameInput:g(ue.cardholderName),expiryInput:g(ue.cardExpiryDate),cvvInput:g(ue.cardSecurityCode)}},removeHostedInputs:()=>{c=!0,e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardholderName.remove()},submit:async g=>{if((await m.validate()).valid)return await t.apiController.setPreferredNetwork(g?.cardNetwork),Ca(r,e)},validate:async()=>{let g=(await Promise.all(Object.entries(l).map(([T,M])=>M?.getFieldState().then(x=>[T,x]).catch(()=>{})))).filter(T=>T!==void 0),h=[];for(let[T,M]of g)!M.valid&&M.error&&h.push({field:T,name:T,error:M.error,message:M.error});return{valid:h.length===0,validationErrors:h}},reset:()=>{Object.values(l).forEach(g=>{g?.reset()}),t.apiController.setPreferredNetwork(void 0)},setCardholderName:g=>{try{l[ue.cardholderName]?.setCardholderName(g)}catch(h){C.errorWithDatadog("SetCardholderName error",{error:h})}}};return m}function mp(r,t){if(r.length!==t.length)return!0;let e=t.map(({network:a})=>a);return!r.every(({network:a})=>e.includes(a))}function hp(r,t,e){return{createButton:()=>({render:async(a,i)=>{await Ca(r,e);let n=typeof a=="string"?document.getElementById(a):a;if(!n)throw new G({code:ou.CONTAINER_NOT_FOUND,message:`Container with id "${a}" not found in the DOM.`});await e.render(n,i)},setDisabled:a=>e.setDisabled(a)})}}function gp(r,t,e){return{start:()=>Ca(r,e)}}function yp(r,t,e){return{start:async a=>(a?.blikCode&&e.setBlikCode(a.blikCode),Ca(r,e))}}function fp(r,t){return{"Content-Type":"application/json","primer-client-token":r,"primer-sdk-client":"WEB","primer-sdk-version":"0.0.0-local","primer-sdk-checkout-session-id":t,"x-api-version":"2.4"}}function vp(r,t,e){if(e?.status&&e.status>=400&&e.status<500)return!1;if(e?.status&&e.status>=500)return!0;if(r instanceof Error){let a=r.message.toLowerCase();return a.includes("network")||a.includes("timeout")||a.includes("connection")}return!1}function Sp(r){let n=1e3*Math.pow(1.1,r),o=.1*n*(Math.random()-.5);return n=Math.max(0,n+o),Math.min(n,3e4)}var bp={attempts:3,retryCondition:vp,delayCalculator:Sp,totalTimeout:3e5};async function Ap(r,t,e){let a={...bp,...t.retry},i=[],n=Date.now();for(let s=0;s<=a.attempts;s++)try{let l=await r();if(!l.error)return{...l,retryHistory:i.length>0?i:void 0};if(s===a.attempts||!a.retryCondition(l.error,s,l))return{...l,retryHistory:i};let c=a.delayCalculator(s);if(i.push({attempt:s+1,delay:c,error:l.error,timestamp:Date.now()}),Date.now()-n+c>a.totalTimeout)return{...l,error:new Ge({message:`Retry total timeout exceeded for ${t.method} ${e}`,code:Aa({status:408}),response:l}),retryHistory:i};await qt(c)}catch(l){i.push({attempt:s+1,delay:0,error:new Ge({message:`Request failed for ${t.method} ${e}`,code:Q.UNEXPECTED,error:l,response:{id:t.id}}),timestamp:Date.now()})}let o=i[i.length-1]?.error;return{id:t.id,error:o,retryHistory:i}}var Xt=class{constructor(t,e="",a={}){k(this,"fetch");k(this,"baseUrl");k(this,"defaultHeaders");this.fetch=t,this.baseUrl=e,this.defaultHeaders=Object.freeze({...a})}setDefaultHeader(t,e){this.defaultHeaders={...this.defaultHeaders,[t]:e}}async executeFetch(t,e){let a={...e,headers:{...this.defaultHeaders,...e?.headers},id:Pe()};return e?.retry?Ap(()=>this.fetch(t,{...a,retry:void 0}),a,t):this.fetch(t,a)}async get(t,e){return this.executeFetch(t,{...e,method:"GET"})}async post(t,e,a){return this.executeFetch(t,{...a,method:"POST",body:JSON.stringify(e)})}async delete(t,e){return this.executeFetch(t,{...e,method:"DELETE"})}};async function Cp(r,t){let e=t.id??Pe(),a={id:e};t.headers??(t.headers={}),t.headers["X-Request-Id"]=e;try{let i=await fetch(r,t);if(a.data=await i.json(),a.status=i.status,a.headers=Object.fromEntries(i.headers.entries()),!i.ok){let n=new Ge({message:`Request failed for ${t.method} ${r}`,code:Aa({backendErrorId:a.data?.error?.errorId,status:a.status}),response:{...a}});a.error=n}}catch(i){let n=new Ge({message:`Request failed for ${t.method} ${r}`,code:Aa({status:a.status}),response:{...a},error:i});a.error=n}return a}var Ui=class extends Xt{constructor(){super(...arguments);k(this,"configurationSubscribers",new Set);k(this,"_configuration")}async getConfiguration(){let e=await this.get(this.baseUrl);return e.data&&(this._configuration=e.data),e}subscribe(e){return this.configurationSubscribers.add(e),()=>{this.configurationSubscribers.delete(e)}}get configuration(){return this._configuration}set configuration(e){this._configuration=e,this.configurationSubscribers.forEach(a=>a(this._configuration))}},Hi=class extends Xt{async getPaymentInstruments(){return this.get(`${this.baseUrl}/payment-instruments`)}async postCardPaymentInstruments(){return this.post(`${this.baseUrl}/payment-instruments`,"pci-card-form-data")}async postPaypalPaymentInstruments(t,e){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,...e})}async postPaymentInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t})}async postRedirectPaymentInstruments(t){return this.postPaymentInstruments(t)}async postApplePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postGooglePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postBlikPaymentInstruments(t){return this.postPaymentInstruments(t)}async postPaymentInstrumentsExchange(t){return this.post(`${this.baseUrl}/payment-instruments/${t}/exchange`,"payment-instrument-exchange")}async postCreatePayment(t,e){return this.post(`${this.baseUrl}/payments`,{paymentMethodToken:t},e?{headers:{"X-Idempotency-Key":e}}:void 0)}async postResumePayment(t,e){return this.post(`${this.baseUrl}/payments/${t}/resume`,{resumeToken:e})}async post3dsAuth(t,e){return this.post(`${this.baseUrl}/3ds/${t}/auth`,e,{retry:{attempts:15}})}async post3dsContinue(t){return this.post(`${this.baseUrl}/3ds/${t}/continue`,{platform:"WEB",status:"FAILURE"})}async get3dsResumeStatus(t){return this.get(t)}async deletePaymentInstrument(t){return this.delete(`${this.baseUrl}/payment-instruments/${t}/vault`)}async postClientSessionActions(t){return this.post(`${this.baseUrl}/client-session/actions`,{actions:t})}async getResumeStatus(t){return this.get(t)}};async function Mp(r){return new Promise((t,e)=>{let a=Zo(r,"api"),i=`${Cu}#${a}`,n=document.querySelector(`iframe[src="${i}"]`)??document.createElement("iframe");n.parentElement?t(n):(n.style.display="none",n.onload=()=>t(n),n.onerror=o=>{e(new Error(`Failed to initialize Primer SDK: ${o}`))},n.src=i,document.body.appendChild(n))})}var _t=class _t extends Xt{constructor(){super(...arguments);k(this,"onClientSessionUpdate");k(this,"onPaymentMethodAction");k(this,"selectedPaymentMethodType",null)}setOnClientSessionUpdate(e){this.onClientSessionUpdate=e}setOnPaymentMethodAction(e){this.onPaymentMethodAction=e}async postClientSessionActions(e){if(e.length===0)return _t.noActionsResponse;let a=await this.post(`${this.baseUrl}/client-session/actions`,{actions:e}),{data:i}=a;return i&&this.onClientSessionUpdate?.(i),a}async selectPaymentMethod(e,a={}){return this.selectedPaymentMethodType===e||(this.selectedPaymentMethodType=e,this.onPaymentMethodAction?.("PAYMENT_METHOD_SELECTED",{paymentMethodType:e}),e==="PAYMENT_CARD"&&!a.binData)?_t.noActionsResponse:this.postClientSessionActions([{type:"SELECT_PAYMENT_METHOD",params:{...a,paymentMethodType:e}}])}async unselectPaymentMethod(){return this.onPaymentMethodAction?.("PAYMENT_METHOD_UNSELECTED",{paymentMethodType:this.selectedPaymentMethodType}),this.selectedPaymentMethodType=null,this.postClientSessionActions([{type:"UNSELECT_PAYMENT_METHOD"}])}async selectCardNetwork(e){return this.selectPaymentMethod(O.PAYMENT_CARD,{binData:this.buildCardBinData(e)})}async setBillingAddress(e){let a=this.removeEmptyStringFromObject(e);return Object.values(a).length===0?_t.noActionsResponse:this.postClientSessionActions([{type:"SET_BILLING_ADDRESS",params:{billingAddress:a}}])}async setShippingAddress(e,a,i){let n=[];return e&&Object.keys(e).some(s=>!!e[s])&&n.push({type:"SET_SHIPPING_ADDRESS",params:{shippingAddress:e}}),a&&n.push({type:"SET_MOBILE_NUMBER",params:{mobileNumber:a}}),i&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:i}}),this.postClientSessionActions(n)}async selectShippingMethod(e){return this.postClientSessionActions([{type:"SELECT_SHIPPING_METHOD",params:{shippingMethodId:e}}])}async setCustomerDetails({emailAddress:e,firstName:a,lastName:i}){let n=[];return e&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:e}}),a&&n.push({type:"SET_CUSTOMER_FIRST_NAME",params:{firstName:a}}),i&&n.push({type:"SET_CUSTOMER_LAST_NAME",params:{lastName:i}}),this.postClientSessionActions(n)}buildCardBinData(e){let{backend:a}=ur(e);return{network:a,issuer_name:null,product_code:a,product_name:a,product_usage_type:"UNKNOWN",account_number_type:"UNKNOWN",issuer_country_code:null,account_funding_type:"UNKNOWN",issuer_currency_code:null,regional_restriction:"UNKNOWN",prepaid_reloadable_indicator:"NOT_APPLICABLE"}}removeEmptyStringFromObject(e){let a={...e};for(let i in a)a[i]===""?delete a[i]:typeof a[i]=="object"&&a[i]!==null&&!Array.isArray(a[i])&&(a[i]=this.removeEmptyStringFromObject(a[i]));return a}};k(_t,"noActionsResponse",{data:{},error:void 0,headers:{},status:200,id:""});var Yi=_t,$i=class extends Xt{async createPaypalOrder(t){return this.post(`${this.baseUrl}/paypal/orders/create`,t,{retry:{attempts:3}})}async createPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/create-agreement`,t,{retry:{attempts:3}})}async confirmPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/confirm-agreement`,t,{retry:{attempts:3}})}async createApplePaySession(t){return this.post(`${this.baseUrl}/apple-pay/sessions`,t)}};async function Ep(r,{locale:t,dialogProvider:e,translate:a,clientOptions:i}){let n=Pe(),o=Jt(r),s=await Mp(n),l=Xi({namespace:`api-controller-${n}`,onMessage:E=>{let L=K=>{if(K.data?.data?.error?.name==="RequestError"){let j=Object.assign(new Ge({...K.data.data.error}),K.data.data.error);typeof j.error=="object"&&"message"in j.error&&(j.error=Object.assign(new Error(j.error.message),{stack:j.error.stack})),K.data.data.error=j}return E(K.data)};return window.addEventListener("message",L),()=>window.removeEventListener("message",L)},sendMessage:E=>{s.contentWindow.postMessage(E,"*")}}),c=fp(o.accessToken,n),m=new Ui(Cp,o.configurationUrl,c),g=Date.now(),{error:h}=await m.getConfiguration();if(h||!m.configuration)throw new Error(`Failed to fetch configuration: ${h}`);let T=new Hi(l.fetch,m.configuration.pciUrl,c),M=new $i(l.fetch,m.configuration.coreUrl,c),x=new Yi(l.fetch,m.configuration.pciUrl,c);x.setOnClientSessionUpdate(E=>{m.configuration=E});let _=new Set;return{get configuration(){return m.configuration},onClientConfigurationUpdate(E){return m.subscribe(E)},checkoutSessionId:n,apiController:l,configurationApi:m,pciApi:T,coreApi:M,clientSessionApi:x,dialogProvider:e,decodedClientToken:o,locale:t||navigator.language||navigator.languages[0]||"en",configurationFetchStartTime:g,translate:a??((E,L)=>L),clientOptions:i,updateClientToken(E){try{let L=Jt(E);m.setDefaultHeader("primer-client-token",L.accessToken),T.setDefaultHeader("primer-client-token",L.accessToken),M.setDefaultHeader("primer-client-token",L.accessToken),x.setDefaultHeader("primer-client-token",L.accessToken)}catch{}},async refreshClientConfiguration(){let{data:E,error:L}=await m.getConfiguration();return L||!E?(C.warn("Failed to refresh client configuration:",L),!1):(m.configuration=E,!0)},subscribeToTeardown(E){return _.add(E),()=>{_.delete(E)}},teardown(){s.remove(),_.forEach(E=>E())}}}var Tp=100;function Pp({height:r,name:t,url:e="",width:a}){let i=new Set,n=window.open(e,t,Ip({height:r,width:a}));if(!n)return;function o(){n?.close(),s()}function s(){i.forEach(l=>l()),i.clear(),window.removeEventListener("beforeunload",o)}return window.addEventListener("beforeunload",o),Np(n).then(s),{close:o,focus(){n.focus()},get isOpen(){return n?.closed===!1},onClose(l){return i.add(l),()=>{i.delete(l)}},setContent(l){n.document.write(l)},setUrl(l){n.location.replace(l)}}}var Np=r=>new Promise(t=>{let e=setInterval(()=>{r.closed&&(clearInterval(e),t())},Tp)});function Ip(r){let t=kp({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:r});return Lp(t)}var kp=({parent:r,popup:t})=>({left:r.left+(r.width-t.width)/2,top:r.top+(r.height-t.height)/2,height:t.height,width:t.width}),Lp=r=>Object.entries(r).map(t=>t.join("=")).join(","),Rp=({name:r,background:t,logoSrc:e,logoAlt:a,message:i})=>`<html>
|
|
37
37
|
<head>
|
|
38
38
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
39
39
|
<style>
|
|
@@ -143,7 +143,7 @@ import{a as Wa,b as q,c as Pi,d,e as k}from"./chunks/chunk.QNO3CTH5.js";var ac=q
|
|
|
143
143
|
</html>
|
|
144
144
|
`,zi=class extends gt{constructor(){super(...arguments);k(this,"popup");k(this,"shouldRedirect",!1);k(this,"dialogPromise")}async start(){try{let e=this.callbacks.onStart();(this.config.forceRedirect||this.context.clientOptions.redirect?.forceRedirect||nu())&&(this.shouldRedirect=!0);let a=document.createElement("div");a.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let i=document.createElement("div");i.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${this.backgroundColor};border-radius:var(--primer-radius-small);`);let n=document.createElement("img");n.src=this.logoSrc,i.appendChild(n),a.appendChild(i);let o=document.createElement("p");o.setAttribute("style","max-width: 300px;text-align: center;"),o.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.config.name),a.appendChild(o),this.dialogPromise=this.context.dialogProvider.show({htmlContent:a,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{this.popup?.focus()}}}),this.shouldRedirect||(this.openPopup(),this.popup&&await qt(300),this.popup?.isOpen||(this.shouldRedirect=!0));let{action:s}=await e;if(s==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let l=await this.tokenize();this.callbacks.onFinish(l)}catch(e){this.context.dialogProvider.close(),this.popup?.close(),this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:a}=await this.context.pciApi.postRedirectPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Uo()?"MOBILE_WEB":"WEB",browserInfo:Qi(),merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!a)throw e??new z({message:"Unable to tokenize payment method",code:F.TOKENIZATION_ERROR});return a}async createPayment(e){try{let a=await super.createPayment(e),i=a.requiredAction?.clientToken;if(!i)throw new z({message:"No client token provided"});let n=Jt(i);if(!tu(n,this.config.type))throw new z({message:"Invalid client token"});if(this.shouldRedirect)return wt({eventName:"PAYMENT_REDIRECT_TO_THIRD_PARTY",paymentMethod:this.config.type,redirectDestinationUrl:n.redirectUrl}),window.location.assign(n.redirectUrl),Promise.resolve(a);if(!this.popup?.isOpen)return this.unselect(),this.context.dialogProvider.close(),{...a,cancelled:!0};this.popup?.setUrl(n.redirectUrl);let o=(this.dialogPromise??Promise.resolve()).then(()=>({id:"",popupClosed:!0})),s=new Promise(h=>{this.popup?.onClose(()=>{C.debug("Popup closed"),h({id:"",popupClosed:!0})})}),{promise:l,abort:c}=this.pollStatus(n.statusUrl),m=await Promise.race([o,s,l]);if(c(),this.popup?.close(),this.context.dialogProvider.close(),"error"in m)throw m.error;if("popupClosed"in m&&m.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure)return this.unselect(),{...a,cancelled:!0};let g=m.id;if(!g){let h=await this.context.pciApi.getResumeStatus(n.statusUrl);if(h.error||!h.data?.id)throw h.error??new Error("Unable to get resume token");g=h.data.id}return await this.resumePayment(a.id,g)}catch(a){throw this.context.dialogProvider.close(),this.popup?.close(),a}}unselect(){this.context.clientSessionApi.unselectPaymentMethod()}pollStatus(e){let a=!0;return{promise:new Promise(async i=>{for(;a;){let{data:n,error:o}=await this.context.pciApi.getResumeStatus(e);if(o)return void i({error:o});if(await qt(1e3),n?.status==="COMPLETE")return void i({id:n.id})}}),abort:()=>{C.debug("Polling aborted"),a=!1}}}openPopup(){let{name:e,displayMetadata:{popup:a}}=this.config;this.popup=Pp({name:e,height:a?.height??500,width:a?.width??1e3}),this.popup?.setContent(Rp({name:e,background:this.backgroundColor,logoSrc:this.logoSrc,logoAlt:e,message:`Loading ${e}...`}))}get backgroundColor(){let{displayMetadata:{button:e,overlay:a}}=this.config;return a?.backgroundColor.colored||e?.backgroundColor.colored||a?.backgroundColor.light||e?.backgroundColor.light||a?.backgroundColor.dark||e?.backgroundColor.dark||"#FFFFFF"}get logoSrc(){let{displayMetadata:{button:e,overlay:a}}=this.config;return a?.logo.colored||e?.iconUrl.colored||a?.logo.light||e?.iconUrl.light||a?.logo.dark||e?.iconUrl.dark}},_p=[O.ADYEN_AFFIRM,O.ADYEN_BANCONTACT_CARD,O.ADYEN_BANCONTACT_PAYCONIQ,O.ADYEN_EPS,O.ADYEN_KLARNA,O.ADYEN_MBWAY,O.ADYEN_MULTIBANCO,O.GO_CARDLESS,O.KLARNA,O.MOLLIE_GIFT_CARD,O.NETS,O.OMISE_PROMPTPAY,O.PAY_NL_KAARTDIRECT,O.PAY_NL_PAYPAL,O.RAPYD_FAST,O.RAPYD_PROMPTPAY,O.STRIPE_ACH,O.XFERS_PAYNOW];async function xp(r,t){let e=r.configuration.paymentMethods.filter(({type:i})=>!t||t.includes(i)).map(i=>{if(_p.includes(i.type))return C.warn(`Payment method ${i.type} is not supported in sdk core.`),null;if(C.debug("Initializing payment method:",i.type),i.implementationType==="WEB_REDIRECT")return new zi(i,r);if(i.type===O.PAYMENT_CARD)return new lr(i,r);if(i.type===O.PAYPAL)return new cr(i,r);if(i.type===O.APPLE_PAY)return new or(i,r);if(i.type===O.GOOGLE_PAY)return new dr(i,r);if(i.type===O.ADYEN_BLIK)return new sr(i,r)}).map(async i=>{if(!i)return null;try{return await i.setup()?i:null}catch(n){return C.warn(`Failed to initialize payment method ${i.config.type}:`,n),null}});return(await Promise.all(e)).filter(i=>!!i)}function wp(r,t,e){if(!t.configuration.clientSession.customer?.customerId)throw new G({message:"You must provide a `customerId` in the client session to use the Vault Manager."});let a=[];return{async fetchVaultedPaymentMethods(){let{data:i,error:n}=await t.pciApi.getPaymentInstruments();if(n)throw n;if(!i)throw new G({code:qa.VAULT_ERROR,message:"Missing vaulted payment methods data"});return a=i.data,a},async deleteVaultedPaymentMethod(i){if(!a.find(s=>s.id===i))throw new G({code:qa.VAULT_ERROR,message:"deleteVaultedPaymentMethod: the id provided doesn't match any vaulted payment method"});let{error:o}=await t.pciApi.deletePaymentInstrument(i);if(o)throw o;a=a.filter(s=>s.id!==i)},async startPaymentFlow(i){let n=a.find(s=>s.id===i);if(!n)throw new G({code:qa.VAULT_ERROR,message:"startPaymentFlow: the id provided doesn't match any vaulted payment method"});let o=e.find(s=>s.config.type===n.paymentMethodType);if(!o)throw new z({code:qa.TOKENIZATION_ERROR,message:`Payment instrument type ${n.paymentInstrumentType} is not recognized or not supported.`});await Ca(r,o,n)},async createCvvInput(i){let n={blur:new Set,change:new Set,focus:new Set},o,s=va(t.checkoutSessionId,lo);await new Promise(h=>{s.onload=()=>{h()},(typeof i.container=="string"?document.querySelector(i.container):i.container)?.appendChild(s)}),Vi(s,i.style),s.setAttribute("title",i.ariaLabel||"");let l=Xi({namespace:`${t.checkoutSessionId}-${lo}`,onMessage:h=>{let T=M=>h(M.data);return window.addEventListener("message",T),()=>window.removeEventListener("message",T)},sendMessage:h=>{s.contentWindow.postMessage(h,"*")}});function c(h,T){h!=="metadata"&&n[h].add(T)}l.setOnFocus(()=>{n.focus.forEach(h=>h())}),l.setOnBlur(()=>{n.blur.forEach(h=>h())}),l.setOnInput(h=>{o=h,n.change.forEach(T=>T())}),l.setCardNetwork(i.cardNetwork??""),l.setOptions({placeholder:i.placeholder??"123",ariaLabel:i.ariaLabel??"CVV",style:i.style});function m(){s.parentNode&&s.remove()}let g=t.subscribeToTeardown(m);return{frame:s,remove:()=>{g(),m()},get metadata(){return{error:o?.error??"cvvRequired",errorCode:o?.error??"cvvRequired",valid:o?.valid??!1,active:o?.focused??!1,dirty:o?.dirty??!1,touched:o?.touched??!1,submitted:!0}},addEventListener:c,addListener:c,removeListener(h,T){h!=="metadata"&&n[h].delete(T)},blur(){l.blur()},focus(){l.focus()},validate(){l.getFieldState().then(h=>{o=h,n.change.forEach(T=>T(o))})}}}}}async function rs(r,t){C.debug("createHeadless",t);let e=await Ep(r,{locale:t.locale,dialogProvider:t.dialogProvider,translate:t.translate,clientOptions:{paypal:t.paypal,applePay:t.applePay,googlePay:t.googlePay,merchantDomain:t.merchantDomain,redirect:t.redirect}}),a=await xp(e,t.enabledPaymentMethods);t.onClientSessionUpdate?.(e.configuration.clientSession),e.onClientConfigurationUpdate(async n=>{t.onClientSessionUpdate?.(n.clientSession)}),t.onPaymentMethodAction&&e.clientSessionApi.setOnPaymentMethodAction(t.onPaymentMethodAction);let i={environment:Fi?"LOCAL":e.decodedClientToken.env,primerAccountId:e.configuration.primerAccountId,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.configuration.clientSession?.clientSessionId,clientSessionToken:r,sdkVersion:t.sdkVersion,configurationFetchStartTime:e.configurationFetchStartTime};return Fc({environment:Fi?"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===O.PAYMENT_CARD?Ni.CARD:n.config.implementationType==="NATIVE_SDK"?Ni.NATIVE:Ni.REDIRECT}))),{start:async()=>{if(e.decodedClientToken.intent==="REDIRECTION_END"){let{data:n,error:o}=await e.pciApi.postResumePayment(e.decodedClientToken.paymentId,e.decodedClientToken.resumeToken);as(t,n,o)}},createPaymentMethodManager:async(n,o)=>{let s=a.find(({config:l})=>l.type===n);return s?s instanceof lr?pp(t,e,s,o):s instanceof cr||s instanceof or||s instanceof dr?hp(t,e,s):s instanceof sr?yp(t,e,s):gp(t,e,s):(C.warn(`Payment method ${n} not found`),null)},getSDKUtilities:()=>({getCardNetworkAsset:Eo,getUIOrderAmount:()=>{let{merchantAmount:n,totalOrderAmount:o,currencyCode:s}=e.configuration.clientSession.order;return Yo(e.locale,n??o,s)},getCDNAssets:async n=>{let o=a.find(({config:c})=>c.type===n);if(!o)return;let{backgroundColor:s,iconUrl:l}=o.config.displayMetadata?.button||{};return{assets:{icon:l?.colored||""},colors:{background:s?.colored||"",main:s?.colored||""},description:o.config.name||null,is_primer_app:!1,name:o.config.name,website:null,goatCdnUrl:""}},getPaymentMethodConfiguration:n=>a.find(({config:o})=>o.type===n)?.config,setBillingAddress:async n=>{let{error:o,data:s}=await e.clientSessionApi.setBillingAddress(n);if(o||!s)throw o||new G({message:"Failed to set billing address"})}}),getAnalyticsUtils:()=>i,createVaultManager(){return wp(t,e,a)},getAssetsManager:()=>({getCardNetworkAsset:Eo,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 Eo=r=>{let{asset:t,display:e}=ur(r);return{cardUrl:`${Eu}/brand/card/${t}.svg`,displayName:e}},Dp=new Set(["paymentMethodType","last4Digits","network","accountNumberLastFourDigits","bankName"]);function ta(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))Dp.has(o)&&(n[o]=s);return i.paymentMethodData=n,i}var Op={PAYMENT_CARD:{fields:["last4Digits","network","cardholderName","expirationMonth","expirationYear"]},PAYPAL_BILLING_AGREEMENT:{path:"externalPayerInfo",fields:["externalPayerId","email","firstName","lastName"]},KLARNA_CUSTOMER_TOKEN:{path:"sessionData.billingAddress",fields:["email","firstName","lastName","phoneNumber"]},AUTOMATED_CLEARING_HOUSE:{fields:["accountNumberLastFourDigits","bankName","accountType"]}};function Bp(r,t){let e=r;for(let a of t.split(".")){if(!e||typeof e!="object")return;e=e[a]}return e&&typeof e=="object"?e:void 0}function Gp(r,t){if(!r)return;let e={};for(let a of t)r[a]!==void 0&&(e[a]=r[a]);return Object.keys(e).length>0?e:void 0}function is(r){let{id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i,paymentInstrumentData:n,userDescription:o}=r,s=Op[i],l;if(s&&n&&typeof n=="object"){let c=s.path?Bp(n,s.path):n;l=Gp(c,s.fields)}return{id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i,...o&&{userDescription:o},...l&&{paymentInstrumentData:l}}}var aa=class{constructor(t){(this.host=t).addController(this)}hostConnected(){}dispatchEvent(t,e){this.host.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}dispatchSdkState(t){this.dispatchEvent("primer:state-change",t)}dispatchPaymentMethods(t){this.dispatchEvent("primer:methods-update",t)}dispatchCheckoutInitialized(t){this.dispatchEvent("primer:ready",t)}dispatchCardNetworkChange(t){this.dispatchEvent("primer:card-network-change",t)}dispatchBinDataAvailable(t){this.dispatchEvent("primer:bin-data-available",t)}dispatchBinDataLoadingChange(t){this.dispatchEvent("primer:bin-data-loading-change",{loading:t})}dispatchCardSubmit(t){this.dispatchEvent("primer:card-submit",{source:t})}dispatchFormSubmitSuccess(t){this.dispatchEvent("primer:card-success",{result:t})}dispatchFormSubmitErrors(t){this.dispatchEvent("primer:card-error",{errors:t})}dispatchPaymentCancel(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-cancel",{...t,timestamp:e})}handleExternalCardSubmit(t){this.dispatchCardSubmit(t.source)}dispatchPaymentStart(t,e){let a=Math.floor(Date.now()/1e3),i=!1,n=new CustomEvent("primer:payment-start",{detail:{paymentMethodType:t,abortPaymentCreation:()=>{i=!0,e.abortPaymentCreation()},continuePaymentCreation:o=>{i=!0,e.continuePaymentCreation(o)},timestamp:a},bubbles:!0,composed:!0,cancelable:!0});return this.host.dispatchEvent(n),n.defaultPrevented?!0:i}dispatchPaymentSuccess(t,e){let a=ta(t),i=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-success",{payment:a,paymentMethodType:e,timestamp:i})}dispatchPaymentFailure(t,e,a){let i=Math.floor(Date.now()/1e3),n=a?ta(a):void 0;this.dispatchEvent("primer:payment-failure",{error:t,payment:n,paymentMethodType:e,timestamp:i})}dispatchVaultMethodsUpdate(t,e){let a=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-methods-update",{vaultedPayments:t,cvvRecapture:e,timestamp:a})}dispatchVaultSelectionChange(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-selection-change",{paymentMethodId:t,timestamp:e})}dispatchVaultSubmit(t){this.dispatchEvent("primer:vault-submit",{source:t})}handleExternalVaultSubmit(t){this.dispatchVaultSubmit(t.source)}dispatchShowOtherPaymentsToggle(t,e){this.dispatchEvent("primer:show-other-payments-toggle",{action:t,source:e})}handleExternalShowOtherPaymentsToggle(t){this.dispatchShowOtherPaymentsToggle(t.action,t.source)}dispatchShowOtherPaymentsToggled(t){this.dispatchEvent("primer:show-other-payments-toggled",{expanded:t})}};var yt=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 ra=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 yt(this.context,this.host,this.t,this.subscribe))}};var mr=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 en=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},W=class extends mr{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 yt(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 en(this.context,this.host))}};function A({context:r,subscribe:t}){return(e,a)=>{typeof a=="object"?a.addInitializer((function(){new ra(this,{context:r,callback:i=>{e.set.call(this,i)},subscribe:t})})):e.constructor.addInitializer((i=>{new ra(i,{context:r,callback:n=>{i[a]=n},subscribe:t})}))}}var ft=Symbol("analytics-context");var Ye=Symbol("events-context");var hr="cardNetworksContext";var ye="clientOptionsContext";var ia="computedStylesContext";var $="headlessInstanceContext";var gr="configuration";var yr="klarnaCategoriesContext";var Z="managerContext";var vt="paymentMethodsContext";var J="sdkStateContext";var fe="vaultManagerContext";var $e="vaultManagerCvvContext";function Kp(r,t,e,a){let i=r,n=e;return{dispatch:o=>{let s=i,l=t(i,o,n);vr(s,l)?i=l:(i=l,a(l))},getState:()=>Object.freeze({...i}),setCallbacks:o=>{n={...n,...o}}}}function vr(r,t,e=0,a=10){if(e>a)return r===t;if(r===t)return!0;if(r==null||t==null||typeof r!="object"||typeof t!="object")return!1;let i=Object.keys(r);if(i.length!==Object.keys(t).length)return!1;for(let n of i){if(!(n in t))return!1;let o=r[n],s=t[n];if(typeof o=="object"&&o!==null&&(typeof s=="object"&&s!==null)){if(!vr(o,s,e+1,a))return!1}else if(o!==s)return!1}return!0}function tn(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 Dt=class{constructor(t,e,a,i,n=()=>{this.host.requestUpdate()}){this.host=t;this.stateHandler=n;this.host.addController(this),this._dispatcher=Kp(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(){}},fr=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 ns={isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null},os=ns;function Fp(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 Sr=class extends Dt{constructor(t){super(t,ns,Fp,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 br=class{constructor(t){this.sdkStateProvider=null;this.paymentMethodsProvider=null;this.paymentManagerProvider=null;this.cardNetworksContext=null;this.vaultManagerCvvProvider=null;this.clientOptionsContext=null;this.headlessUtilsProvider=null;this.configurationProvider=null;this.klarnaCategoriesProvider=null;this.computedStylesProvider=null;this.analyticsProvider=null;this.eventsProvider=null;(this.host=t).addController(this),this.sdkStateProvider=new W(t,{context:J,initialValue:os}),this.paymentMethodsProvider=new W(t,{context:vt,initialValue:null}),this.paymentManagerProvider=new W(t,{context:Z,initialValue:new Map}),this.cardNetworksContext=new W(t,{context:hr,initialValue:null}),this.vaultManagerProvider=new W(t,{context:fe,initialValue:null}),this.vaultManagerCvvProvider=new W(t,{context:$e,initialValue:null}),this.clientOptionsContext=new W(t,{context:ye,initialValue:null}),this.klarnaCategoriesProvider=new W(t,{context:yr,initialValue:{categories:[],isLoading:!0}}),this.headlessUtilsProvider=new W(t,{context:$,initialValue:null}),this.configurationProvider=new W(t,{context:gr,initialValue:null}),this.computedStylesProvider=new W(t,{context:ia,initialValue:null}),this.analyticsProvider=new W(t,{context:ft,initialValue:null}),this.eventsProvider=new W(t,{context:Ye,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 an=class{constructor(){k(this,"context",null)}initialize(t){this.context=t,P.debug("Session context initialized:",{checkoutSessionId:t.checkoutSessionId,clientSessionId:t.clientSessionId,primerAccountId:t.primerAccountId,environment:t.environment})}getContext(){return this.context}clear(){P.debug("Session context cleared"),this.context=null}isInitialized(){return this.context!==null}setSdkInitStartTime(t){this.context&&(this.context.sdkInitStartTime=t)}getSdkInitStartTime(){return this.context?.sdkInitStartTime}},ze=new an;var Vp={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 ss(r,t={}){let e=ze.getContext();if(!e&&!t?.environment)return;let i={message:r instanceof Error?r.message:typeof r=="string"?r:JSON.stringify(r)};r instanceof Error&&r.stack&&(i.stack=r.stack),e?Object.assign(i,{primer:{checkout_session_id:e.checkoutSessionId,client_session_id:e.clientSessionId,primer_account_id:e.primerAccountId},user_agent:e.userAgent}):(t?.checkoutSessionId&&Object.assign(i,{primer:{checkout_session_id:t.checkoutSessionId}}),t?.clientSessionId&&Object.assign(i,{primer:{client_session_id:t.clientSessionId}}),t?.primerAccountId&&Object.assign(i,{primer:{primer_account_id:t.primerAccountId}}),t?.userAgent&&Object.assign(i,{user_agent:t.userAgent})),t?.metadata&&Object.assign(i,t.metadata),t.status&&(i.status=t.status);let n={message:JSON.stringify(i),hostname:typeof window<"u"?window.location.hostname:"unknown",service:"web-sdk",ddsource:"lambda",ddtags:`env:${e?.environment||t?.environment},version:${e?.sdkVersion||t?.sdkVersion}`};Up(n,{environment:e?.environment||t?.environment,clientSessionToken:e?.clientSessionToken||t?.clientSessionToken})}var ls=(r,t={})=>ss(r,{...t,status:"error"});function ds(r){let t={event:"CHECKOUT_INITIALIZED"};r!==void 0&&(t.init_duration_ms=r),ss("Checkout initialized",{status:"info",metadata:t})}function Up(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"||r.hostname==="localhost"){P.debug("\u{1F436}\u{1F436}\u{1F436} [Datadog Log] \u{1F436}\u{1F436}\u{1F436}",r);return}let a=Vp[t||"LOCAL"];if(!a){P.warn("No logging endpoint configured for current environment");return}fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{P.error("Failed to send log event:",i)})}var H=class H{static _log(t,e,...a){H.enabled&&a.forEach(i=>{i instanceof Error&&i.toJSON})}static log(t,...e){H._log("log",t,...e)}static info(t,...e){H._log("info",t,...e)}static warn(t,...e){H._log("warn",t,...e)}static error(t,...e){H._log("error",t,...e)}static debug(t,...e){this._log("debug",t,...e)}static errorWithDatadog(t,e){let{error:a,status:i="error"}=e||{};if(H.enabled){a instanceof Error&&a.toJSON;try{let n={status:i,metadata:{sdkOptions:H.sdkOptions,clientToken:H.clientToken,error:a}};ls(t,n)}catch{H.enabled}}}static setSdkOptions(t){H.sdkOptions=t}static setClientToken(t){H.clientToken=t}};k(H,"enabled",!0),k(H,"sdkOptions"),k(H,"clientToken"),k(H,"defaultFont","font-family: Consolas, monospace; font-size: 12px;"),k(H,"brandTag","[PRIMER]"),k(H,"brandStyle",`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${H.defaultFont}`),k(H,"styles",{log:`color: #4CAF50; ${H.defaultFont}`,info:`color: #2196F3; ${H.defaultFont}`,warn:`color: #FF9800; ${H.defaultFont}`,error:`color: #F44336; ${H.defaultFont}`,debug:`color: #9C27B0; ${H.defaultFont}`});var P=H;var Ot=class Ot{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){P.error("Error parsing customStyles property.",e instanceof Error?e:new Error(String(e)))}}isValidCssProperty(t){return/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)}isValidCssValue(t){let a=/^[\w\s#.,%()\-+/!]+$/.test(t);return a||P.warn(`Rejected potentially unsafe CSS value: ${t}`),a}getCssVarName(t){let e=Ot.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(a,i)=>`-${i.toLowerCase()}`)}`,Ot.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let a of Object.keys(t)){let i=t[a];if(!i)continue;if(!this.isValidCssProperty(a)){P.warn(`Skipping invalid CSS property name: ${a}`);continue}if(!this.isValidCssValue(i))continue;let n=this.getCssVarName(a);e.push([n,i])}if(e.length>0)for(let[a,i]of e)this.host.style.setProperty(a,i)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of Ot.cssVarCache.keys()){let e=Ot.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};Ot.cssVarCache=new Map;var Ar=Ot;var Cr=globalThis,Er=Cr.ShadowRoot&&(Cr.ShadyCSS===void 0||Cr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,us=Symbol(),cs=new WeakMap,Mr=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==us)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(Er&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=cs.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&cs.set(e,t))}return t}toString(){return this.cssText}},ps=r=>new Mr(typeof r=="string"?r:r+"",void 0,us);var rn=(r,t)=>{if(Er)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=Cr.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},Tr=Er?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return ps(e)})(r):r;var{is:Hp,defineProperty:Yp,getOwnPropertyDescriptor:$p,getOwnPropertyNames:zp,getOwnPropertySymbols:jp,getPrototypeOf:Wp}=Object,St=globalThis,ms=St.trustedTypes,Zp=ms?ms.emptyScript:"",Jp=St.reactiveElementPolyfillSupport,Ma=(r,t)=>r,nn={toAttribute(r,t){switch(t){case Boolean:r=r?Zp: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}},Pr=(r,t)=>!Hp(r,t),hs={attribute:!0,type:String,converter:nn,reflect:!1,hasChanged:Pr};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),St.litPropertyMetadata??(St.litPropertyMetadata=new WeakMap);var Bt=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=hs){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&&Yp(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=$p(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)??hs}static _$Ei(){if(this.hasOwnProperty(Ma("elementProperties")))return;let t=Wp(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Ma("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Ma("properties"))){let e=this.properties,a=[...zp(e),...jp(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(Tr(i))}else t!==void 0&&e.push(Tr(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 rn(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,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:nn).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:nn;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??Pr)(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){}};Bt.elementStyles=[],Bt.shadowRootOptions={mode:"open"},Bt[Ma("elementProperties")]=new Map,Bt[Ma("finalized")]=new Map,Jp?.({ReactiveElement:Bt}),(St.reactiveElementVersions??(St.reactiveElementVersions=[])).push("2.0.4");var bt={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},w=Symbol(),B=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??gs,this.k=i.onComplete,this.A=i.onError,this.autoRun=i.autoRun??!0,"initialValue"in i&&(this.u=i.initialValue,this.i=2,this.O=this.T?.())}hostUpdate(){this.autoRun===!0&&this.S()}hostUpdated(){this.autoRun==="afterUpdate"&&this.S()}T(){if(this.j===void 0)return;let t=this.j();if(!Array.isArray(t))throw Error("The args function must return an array");return t}async S(){let t=this.T(),e=this.O;this.O=t,t===e||t===void 0||e!==void 0&&this.m(e,t)||await this.run(t)}async run(t){let e,a;t??(t=this.T()),this.O=t,this.i===1?this.q?.abort():(this.t=void 0,this.o=void 0,this.h=void 0),this.i=1,this.autoRun==="afterUpdate"?queueMicrotask((()=>this._.requestUpdate())):this._.requestUpdate();let i=++this.p;this.q=new AbortController;let n=!1;try{e=await this.v(t,{signal:this.q.signal})}catch(o){n=!0,a=o}if(this.p===i){if(e===w)this.i=0;else{if(n===!1){try{this.k?.(e)}catch{}this.i=2,this.o?.(e)}else{try{this.A?.(a)}catch{}this.i=3,this.h?.(a)}this.u=e,this.l=a}this._.requestUpdate()}}abort(t){this.i===1&&this.q?.abort(t)}get value(){return this.u}get error(){return this.l}get status(){return this.i}render(t){switch(this.i){case 0:return t.initial?.();case 1:return t.pending?.();case 2:return t.complete?.(this.value);case 3:return t.error?.(this.error);default:throw Error("Unexpected status: "+this.i)}}},gs=(r,t)=>r===t||r.length===t.length&&r.every(((e,a)=>!Pr(e,t[a])));var qp={SET_LOADING:(r,t)=>({...r,isLoading:t.payload}),SET_UPDATING:(r,t)=>({...r,isUpdating:t.payload}),INITIALIZE_VAULT_MANAGER:(r,t,e)=>({...r,enabled:t.vaultEnabled,cvvRecapture:t.cvvRecapture,showEmptyState:t.showEmptyState,headless:t.headless,deleteVaultedPaymentMethod:e.deleteVaultedPaymentMethod,startVaultedPaymentFlow:e.startVaultedPaymentFlow,createCvvInput:e.createCvvInput}),UPDATE_PAYMENT_METHODS:(r,t)=>({...r,vaultedPaymentMethods:t.payload,isLoading:!1,isUpdating:!1}),SET_ERROR:r=>({...r,isLoading:!1,isUpdating:!1}),DISABLE:r=>({...r,enabled:!1}),RESET:()=>ys},Qp={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:()=>fs},Xp=tn(qp),em=tn(Qp),ys={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!1,headless:!1,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},fs={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},on=class extends Dt{constructor(t,e){super(t,ys,Xp,e,a=>{t.sdkContextController.setVaultManager(a)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setUpdating(t){this.dispatch({type:"SET_UPDATING",payload:t})}initializeVaultManager(t,e,a,i,n){this.dispatch({type:"INITIALIZE_VAULT_MANAGER",payload:t,vaultEnabled:e,cvvRecapture:a,showEmptyState:i,headless:n})}updatePaymentMethods(t){this.dispatch({type:"UPDATE_PAYMENT_METHODS",payload:t})}setError(t){this.dispatch({type:"SET_ERROR",payload:t})}disable(){this.dispatch({type:"DISABLE"})}reset(){this.dispatch({type:"RESET"})}},sn=class extends Dt{constructor(t,e){super(t,fs,em,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"})}},Ea=class extends fr{constructor(e){super(e);this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(e)};this.deleteVaultedPaymentMethod=async e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.coreController.updatePaymentMethods(this.vaultManagerState.vaultedPaymentMethods),await this._vaultManager.deleteVaultedPaymentMethod(e),await this.fetchVaultedPaymentMethods()}catch(a){let i=a instanceof Error?a:new Error("Failed to delete payment method");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}};this.setCvvInput=e=>{this.itemController.setCvvInputState(e)};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let e=this.vaultItemState.selectedVaultedPaymentMethod,a=this.vaultManagerState.cvvRecapture,i=this.vaultItemState.cvvInput;if(!e||a&&(!i||i.metadata.error)){this.itemController.setFormDirty(!0);return}this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e.id,a?{cvv:i.valueToken}:void 0)}catch(n){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:n});let o=n instanceof Error?n:new Error("Failed to start vaulted payment flow");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o),this.host.sdkStateController.stopProcessing()}};this.setSelectedVaultedPaymentMethod=e=>{this.itemController.setSelectedPaymentMethod(e),this.itemController.setFormDirty(!1),this.host.primerEventsController.dispatchVaultSelectionChange(e?.id??null)};this.startVaultPaymentById=async(e,a)=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let i=this.vaultManagerState.vaultedPaymentMethods.find(n=>n.id===e);if(!i)throw new Error(`Payment method not found: ${e}`);this.setSelectedVaultedPaymentMethod(i),this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e,a?.cvv?{cvv:a.cvv}:void 0)}catch(n){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:n});let o=n instanceof Error?n:new Error("Failed to start vaulted payment flow");throw this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o),this.host.sdkStateController.stopProcessing(),n}};this.coreController=new on(e,{deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.itemController=new sn(e,{setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)}),this.addController(this.coreController),this.addController(this.itemController),new B(this.host,{task:async([a,i])=>{if(!a||!i?.vaultEnabled)return this.coreController.disable(),w;this.coreController.setLoading(!0);try{let n=a();this._vaultManager=n,this.coreController.initializeVaultManager(n,i.vaultEnabled,!!i.captureVaultedCardCvv,i.showEmptyState??!1,i.headless??!1),this.itemController.initializeCvv(n.createCvvInput),await this.fetchVaultedPaymentMethods(!0),P.log("VaultManagerController: Vault initialized successfully",{coreState:this.coreController.currentState,cvvState:this.itemController.currentState})}catch(n){P.errorWithDatadog("VaultManagerController: Failed to initialize vault",{error:n});let o=n instanceof Error?n:new Error("Unknown error");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o)}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}initializeVaultManager(e,a){this.createVaultManagerFn=e,this.options=a??null}get vaultManager(){return this._vaultManager}set vaultManager(e){this._vaultManager=e,this.host.requestUpdate()}get options(){return this._options}set options(e){this._options=e,this.host.requestUpdate()}get vaultManagerState(){return this.coreController.currentState}get vaultItemState(){return this.itemController.currentState}hostDisconnected(){super.hostDisconnected(),this.vaultManager=null,this.coreController.reset()}createVaultedPaymentsArray(e){return e.map(a=>is(a))}updatePaymentMethodsWithEvents(e){this.coreController.updatePaymentMethods(e);let a=this.createVaultedPaymentsArray(e);this.host.primerEventsController.dispatchVaultMethodsUpdate(a,this.vaultManagerState.cvvRecapture),this.host.primerJS?.handleVaultedMethodsUpdate(a,this.vaultManagerState.cvvRecapture),P.log("VaultManagerController: Dispatched vault methods update",{methodCount:e.length,filteredMethodCount:a.length})}async fetchVaultedPaymentMethods(e){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{e||this.coreController.setUpdating(!0);let a=await this._vaultManager.fetchVaultedPaymentMethods();return P.log("VaultManagerController: Fetched payment methods",a),this.updatePaymentMethodsWithEvents(a),a}catch(a){let i=a instanceof Error?a:new Error("Failed to fetch payment methods");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}}};var vs=()=>Ss.randomUUID?.()||tm(),tm=()=>("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,r=>(r^am()>>r/4).toString(16)),am=()=>(Ss.getRandomValues?.(new Uint8Array(1))[0]??Math.random()*16)&15,Ss=typeof crypto<"u"?crypto:{};var rm={LOCAL:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",DEV:"https://analytics.dev.data.primer.io/v1/sdk-analytic-events",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-analytic-events",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-analytic-events"},ln=class{sendEvent(t){let e=ze.getContext();if(!e)return;let a={id:vs(),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};nm(a,e)}},im=new ln;function bs(r){let t={...r,userAgent:r.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};ze.initialize(t)}function X(r){im.sendEvent(r)}function As(){ze.clear()}async function nm(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){P.debug(`Analytics event ${r.eventName}:`,r);return}let a=rm[t];return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{P.error("Failed to send analytics event:",i)})}var Ta="lit-localize-status";var Cs=r=>typeof r!="string"&&"strTag"in r,Nr=(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 Pa=(r=>Cs(r)?Nr(r.strings,r.values):r);var b=Pa,Ms=!1;function dn(r){if(Ms)throw new Error("lit-localize can only be configured once");b=r,Ms=!0}var cn=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(Ta,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(Ta,this.__litLocalizeEventHandler)}},om=r=>r.addController(new cn(r)),Es=om;var D=()=>(r,t)=>(r.addInitializer(Es),r);var Na=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 rt=[];for(let r=0;r<256;r++)rt[r]=(r>>4&15).toString(16)+(r&15).toString(16);function Ts(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 rt[l>>8]+rt[l&255]+rt[o>>8]+rt[o&255]+rt[i>>8]+rt[i&255]+rt[e>>8]+rt[e&255]}var sm="",lm="h",dm="s";function Ps(r,t){return(t?lm:dm)+Ts(typeof r=="string"?r:r.join(sm))}var Ns=new WeakMap,Is=new Map;function ks(r,t,e){if(r){let a=e?.id??cm(t),i=r[a];if(i){if(typeof i=="string")return i;if("strTag"in i)return Nr(i.strings,t.values,i.values);{let n=Ns.get(i);return n===void 0&&(n=i.values,Ns.set(i,n)),{...i,values:n.map(o=>t.values[o])}}}}return Pa(t)}function cm(r){let t=typeof r=="string"?r:r.strings,e=Is.get(t);return e===void 0&&(e=Ps(t,typeof r!="string"&&!("strTag"in r)),Is.set(t,e)),e}function un(r){window.dispatchEvent(new CustomEvent(Ta,{detail:r}))}var kr="",pn,Ls,Lr,mn,Rs,Gt=new Na;Gt.resolve();var Ir=0,_s=r=>(dn(((t,e)=>ks(Rs,t,e))),kr=Ls=r.sourceLocale,Lr=new Set(r.targetLocales),Lr.add(r.sourceLocale),mn=r.loadLocale,{getLocale:um,setLocale:pm}),um=()=>kr,pm=r=>{if(r===(pn??kr))return Gt.promise;if(!Lr||!mn)throw new Error("Internal error");if(!Lr.has(r))throw new Error("Invalid locale code");Ir++;let t=Ir;return pn=r,Gt.settled&&(Gt=new Na),un({status:"loading",loadingLocale:r}),(r===Ls?Promise.resolve({templates:void 0}):mn(r)).then(a=>{Ir===t&&(kr=r,pn=void 0,Rs=a.templates,un({status:"ready",readyLocale:r}),Gt.resolve())},a=>{Ir===t&&(un({status:"error",errorLocale:r,errorMessage:a.toString()}),Gt.reject(a))}),Gt.promise};var hn="en",gn=["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"],yn="You must call `loadLocale` first to set up the localized template.",Rr,_r,xs=r=>{let t=_s({sourceLocale:hn,targetLocales:gn,loadLocale:r});Rr=t.getLocale,_r=t.setLocale};var fn=r=>{xs(r)},vn=r=>{if(!_r)throw new Error(yn);return _r(r)},Sn=()=>{if(!Rr)throw new Error(yn);return Rr()};var Ia=new Set(gn);Ia.add(hn);var bn=r=>{if(typeof r!="string")return!1;if(r==="en")return!0;let t=r.replace("_","-");if(Ia.has(t))return!0;let e=t.split("-")[0];return!!Ia.has(e)},xr=()=>navigator.language||navigator.languages[0]||"en",na=r=>{let t=r.replace("_","-"),e=t.split("-")[0];return e==="en"?"en-GB":Ia.has(t)?t:Ia.has(e)?e:"en-GB"};var wr=globalThis,Dr=wr.ShadowRoot&&(wr.ShadyCSS===void 0||wr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,An=Symbol(),ws=new WeakMap,ka=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==An)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(Dr&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=ws.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&ws.set(e,t))}return t}toString(){return this.cssText}},ve=r=>new ka(typeof r=="string"?r:r+"",void 0,An),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 ka(e,r,An)},Ds=(r,t)=>{if(Dr)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=wr.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},Cn=Dr?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return ve(e)})(r):r;var{is:mm,defineProperty:hm,getOwnPropertyDescriptor:gm,getOwnPropertyNames:ym,getOwnPropertySymbols:fm,getPrototypeOf:vm}=Object,At=globalThis,Os=At.trustedTypes,Sm=Os?Os.emptyScript:"",bm=At.reactiveElementPolyfillSupport,La=(r,t)=>r,Ra={toAttribute(r,t){switch(t){case Boolean:r=r?Sm: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}},Or=(r,t)=>!mm(r,t),Bs={attribute:!0,type:String,converter:Ra,reflect:!1,useDefault:!1,hasChanged:Or};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),At.litPropertyMetadata??(At.litPropertyMetadata=new WeakMap);var it=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=Bs){if(e.state&&(e.attribute=!1),this._$Ei(),this.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&&hm(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=gm(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)??Bs}static _$Ei(){if(this.hasOwnProperty(La("elementProperties")))return;let t=vm(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(La("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(La("properties"))){let e=this.properties,a=[...ym(e),...fm(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(Cn(i))}else t!==void 0&&e.push(Cn(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 Ds(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:Ra).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:Ra;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??Or)(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){}};it.elementStyles=[],it.shadowRootOptions={mode:"open"},it[La("elementProperties")]=new Map,it[La("finalized")]=new Map,bm?.({ReactiveElement:it}),(At.reactiveElementVersions??(At.reactiveElementVersions=[])).push("2.1.0");var xa=globalThis,Br=xa.trustedTypes,Gs=Br?Br.createPolicy("lit-html",{createHTML:r=>r}):void 0,En="$lit$",nt=`lit$${Math.random().toFixed(9).slice(2)}$`,Tn="?"+nt,Am=`<${Tn}>`,Vt=document,wa=()=>Vt.createComment(""),Da=r=>r===null||typeof r!="object"&&typeof r!="function",Pn=Array.isArray,Ys=r=>Pn(r)||typeof r?.[Symbol.iterator]=="function",Mn=`[
|
|
145
145
|
\f\r]`,_a=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ks=/-->/g,Fs=/>/g,Kt=RegExp(`>|${Mn}(?:([^\\s"'>=/]+)(${Mn}*=${Mn}*(?:[^
|
|
146
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),Vs=/'/g,Us=/"/g,$s=/^(?:script|style|textarea|title)$/i,Nn=r=>(t,...e)=>({_$litType$:r,strings:t,values:e}),p=Nn(1),Ke=Nn(2),Zv=Nn(3),Se=Symbol.for("lit-noChange"),y=Symbol.for("lit-nothing"),Hs=new WeakMap,Ft=Vt.createTreeWalker(Vt,129);function zs(r,t){if(!Pn(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Gs!==void 0?Gs.createHTML(t):t}var js=(r,t)=>{let e=r.length-1,a=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=_a;for(let s=0;s<e;s++){let l=r[s],c,m,g=-1,h=0;for(;h<l.length&&(o.lastIndex=h,m=o.exec(l),m!==null);)h=o.lastIndex,o===_a?m[1]==="!--"?o=Ks:m[1]!==void 0?o=Fs:m[2]!==void 0?($s.test(m[2])&&(i=RegExp("</"+m[2],"g")),o=Kt):m[3]!==void 0&&(o=Kt):o===Kt?m[0]===">"?(o=i??_a,g=-1):m[1]===void 0?g=-2:(g=o.lastIndex-m[2].length,c=m[1],o=m[3]===void 0?Kt:m[3]==='"'?Us:Vs):o===Us||o===Vs?o=Kt:o===Ks||o===Fs?o=_a:(o=Kt,i=void 0);let T=o===Kt&&r[s+1].startsWith("/>")?" ":"";n+=o===_a?l+Am:g>=0?(a.push(c),l.slice(0,g)+En+l.slice(g)+nt+T):l+nt+(g===-2?s:T)}return[zs(r,n+(r[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),a]},Oa=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]=js(t,e);if(this.el=r.createElement(c,a),Ft.currentNode=this.el.content,e===2||e===3){let g=this.el.content.firstChild;g.replaceWith(...g.childNodes)}for(;(i=Ft.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let g of i.getAttributeNames())if(g.endsWith(En)){let h=m[o++],T=i.getAttribute(g).split(nt),M=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:M[2],strings:T,ctor:M[1]==="."?Kr:M[1]==="?"?Fr:M[1]==="@"?Vr:Ht}),i.removeAttribute(g)}else g.startsWith(nt)&&(l.push({type:6,index:n}),i.removeAttribute(g));if($s.test(i.tagName)){let g=i.textContent.split(nt),h=g.length-1;if(h>0){i.textContent=Br?Br.emptyScript:"";for(let T=0;T<h;T++)i.append(g[T],wa()),Ft.nextNode(),l.push({type:2,index:++n});i.append(g[h],wa())}}}else if(i.nodeType===8)if(i.data===Tn)l.push({type:2,index:n});else{let g=-1;for(;(g=i.data.indexOf(nt,g+1))!==-1;)l.push({type:7,index:n}),g+=nt.length-1}n++}}static createElement(t,e){let a=Vt.createElement("template");return a.innerHTML=t,a}};function Ut(r,t,e=r,a){if(t===Se)return t;let i=a!==void 0?e._$Co?.[a]:e._$Cl,n=Da(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=Ut(r,i._$AS(r,t.values),i,a)),t}var Gr=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:a}=this._$AD,i=(t?.creationScope??Vt).importNode(e,!0);Ft.currentNode=i;let n=Ft.nextNode(),o=0,s=0,l=a[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new oa(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new Ur(n,this,t)),this._$AV.push(c),l=a[++s]}o!==l?.index&&(n=Ft.nextNode(),o++)}return Ft.currentNode=Vt,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++}},oa=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,a,i){this.type=2,this._$AH=y,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=a,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Ut(this,t,e),Da(t)?t===y||t==null||t===""?(this._$AH!==y&&this._$AR(),this._$AH=y):t!==this._$AH&&t!==Se&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ys(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==y&&Da(this._$AH)?this._$AA.nextSibling.data=t:this.T(Vt.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=Oa.createElement(zs(a.h,a.h[0]),this.options)),a);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new Gr(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=Hs.get(t.strings);return e===void 0&&Hs.set(t.strings,e=new Oa(t)),e}k(t){Pn(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(wa()),this.O(wa()),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))}},Ht=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,a,i,n){this.type=1,this._$AH=y,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,a.length>2||a[0]!==""||a[1]!==""?(this._$AH=Array(a.length-1).fill(new String),this.strings=a):this._$AH=y}_$AI(t,e=this,a,i){let n=this.strings,o=!1;if(n===void 0)t=Ut(this,t,e,0),o=!Da(t)||t!==this._$AH&&t!==Se,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ut(this,s[a+l],e,l),c===Se&&(c=this._$AH[l]),o||(o=!Da(c)||c!==this._$AH[l]),c===y?t=y:t!==y&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===y?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Kr=class extends Ht{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===y?void 0:t}},Fr=class extends Ht{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==y)}},Vr=class extends Ht{constructor(t,e,a,i,n){super(t,e,a,i,n),this.type=5}_$AI(t,e=this){if((t=Ut(this,t,e,0)??y)===Se)return;let a=this._$AH,i=t===y&&a!==y||t.capture!==a.capture||t.once!==a.once||t.passive!==a.passive,n=t!==y&&(a===y||i);i&&this.element.removeEventListener(this.name,this,a),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Ur=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){Ut(this,t)}},Ws={M:En,P:nt,A:Tn,C:1,L:js,R:Gr,D:Ys,V:Ut,I:oa,H:Ht,N:Fr,U:Vr,B:Kr,F:Ur},Cm=xa.litHtmlPolyfillSupport;Cm?.(Oa,oa),(xa.litHtmlVersions??(xa.litHtmlVersions=[])).push("3.3.0");var Zs=(r,t,e)=>{let a=e?.renderBefore??t,i=a._$litPart$;if(i===void 0){let n=e?.renderBefore??null;a._$litPart$=i=new oa(t.insertBefore(wa(),n),n,void 0,e??{})}return i._$AI(r),i};var Ba=globalThis,v=class extends it{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=Zs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Se}};v._$litElement$=!0,v.finalized=!0,Ba.litElementHydrateSupport?.({LitElement:v});var Mm=Ba.litElementPolyfillSupport;Mm?.({LitElement:v});(Ba.litElementVersions??(Ba.litElementVersions=[])).push("4.2.0");var S=r=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(r,t)})):customElements.define(r,t)};var Em={attribute:!0,type:String,converter:Ra,reflect:!1,hasChanged:Or},Tm=(r=Em,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"?Tm(r,t,e):((a,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,a),o?Object.getOwnPropertyDescriptor(i,n):void 0})(r,t,e)}function N(r){return u({...r,state:!0,attribute:!1})}var Yt=(r,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(r,t,e),e);function _e(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 Yt(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 Yt(e,a,{get(){return n(this)}})}}function R(r,t,e){return r?t(r):e?.(r)}var I=f` * { box-sizing: border-box; } `,Js=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 qs="https://sdk.primer.io/web/v2-latest/Primer.min.js",be="20px";var Hr=class{constructor(t){this.paymentMethods=null;this.paymentManagers=null;this.vaultController=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,a)=>this.startVaultPaymentInternal(e,a),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=t}setPaymentManagers(t){this.paymentManagers=t}setVaultController(t){this.vaultController=t}async createCvvInputInternal(t){return this.vaultController?this.vaultController.createCvvInput(t):(P.warn("PrimerJS: Vault not available - createCvvInput cannot be called"),null)}async startVaultPaymentInternal(t,e){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.startVaultPaymentById(t,e)}async deleteVaultPaymentMethod(t){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.deleteVaultedPaymentMethod(t)}async createCvvInput(t){return this.vault.createCvvInput(t)}async startVaultPayment(t,e){return this.vault.startPayment(t,e)}async refreshSession(){if(!this.headlessInstance){P.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw P.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods:(P.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let a=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:a})}}setCardholderName(t){if(!this.paymentManagers){P.warn("PrimerJS: Payment managers not available - setCardholderName cannot be called yet");return}let e=this.paymentManagers.get("PAYMENT_CARD");if(!e||e.type!=="PAYMENT_CARD"){P.warn("PrimerJS: Card payment manager not available");return}try{e.manager.setCardholderName(t)}catch(a){P.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:a})}}};var Yr=typeof window<"u"&&typeof window.document<"u";function Pm(r){return document.querySelector(`script[src^="${r}"]`)}function Nm(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 Qs(r,t=!1){if(!Yr)throw new Error("Cannot load script in server environment");let e=Pm(r)??Nm(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 Xs=f` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var oe=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.open=!1}openDialog(){this.open=!0}closeDialog(){let e=()=>{this.open=!1,this.removeEventListener("primer:dialog-close",e)};this.addEventListener("primer:dialog-close",e),this.dialog.startExitAnimation()}connectedCallback(){super.connectedCallback(),this.open||this.openDialog()}updated(e){super.updated(e),e.has("open")&&this.open&&this.onOpen&&this.onOpen(),e.has("open")&&this.open&&this.onContentRendered&&this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.onContentRendered?.()})})}render(){return this.open?p`<primer-dialog .open=${this.open} size=${this.size} .showCloseButton=${this.showCloseButton} @primer:dialog-close="${()=>{this.open=!1}}" ><slot></slot>${this.cta?p`<primer-button @click=${this.cta.onClick} class="cta-button">${this.cta.icon?p`<primer-icon name="${this.cta.icon}" size="sm" color="var(--primer-color-background-outlined-default)" ></primer-icon>`:y} ${this.cta.label}</primer-button>`:y}</primer-dialog>`:y}};oe.styles=[I,Xs],d([u({type:String})],oe.prototype,"size",2),d([u({type:Boolean})],oe.prototype,"showCloseButton",2),d([u({type:Object})],oe.prototype,"onOpen",2),d([u({type:Object})],oe.prototype,"onContentRendered",2),d([u({type:Object})],oe.prototype,"cta",2),d([N()],oe.prototype,"open",2),d([_e("primer-dialog")],oe.prototype,"dialog",2),oe=d([S("primer-portal-dialog"),D()],oe);var $r=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let a=new oe;a.size=t.size??"large",a.showCloseButton=t.showCloseButton??!1,a.onContentRendered=t.onContentReady,a.cta=t.cta;let i=()=>{a.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};a.addEventListener("primer:dialog-close",i),this.currentDialog=a,this.currentResolver=e,document.body.appendChild(a),a.appendChild(t.htmlContent)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}};var Im=Wa({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});var sa=null,In=null;async function el(r){if(In===r&&sa)return sa;try{return sa=(await Im(`../../../localization/lit-localize/locales/${r}.ts`)).templates,In=r,sa}catch{return r!=="en-GB"?el("en-GB"):(sa={},In=r,sa)}}async function tl(r){let t=await el(r);return(e,a)=>t[e]??a}var Ct={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"},Ga={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"};var zr=class r extends Error{constructor(t,e){super(e.message),this.name="PrimerClientError",this.code=t,this.diagnosticsId=e.diagnosticsId||null,this.data=e.data,this.isFromDeveloper=e.isFromDeveloper||!1}static fromErrorCode(t,e){return new r(t,e)}};function al(r,t,e){return r.isDisconnected?!1:(r.host.sdkStateController.currentState.paymentFailure!==null&&X({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),r.host.sdkStateController.startProcessing(),r.host.primerEventsController.dispatchPaymentStart(t,e))}function rl(r,t,e){if(!r.isDisconnected&&(P.info("Payment completed:",t),r.host.sdkStateController.completeProcessing(),r.host.primerEventsController.dispatchPaymentSuccess(t,e),X({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),r.primerJS?.onPaymentSuccess)){let a=Math.floor(Date.now()/1e3);r.primerJS.onPaymentSuccess({payment:ta(t),paymentMethodType:e,timestamp:a})}}function il(r,t,e,a){if(r.isDisconnected)return;(s=>typeof s=="object"&&s!==null&&"response"in s&&typeof s.response=="object"&&s.response!==null&&"status"in s.response&&typeof s.response.status=="number")(t)&&t.response.status>=500?P.errorWithDatadog("Payment failed with server error",{error:t}):P.error("Payment failed:",t);let o=t instanceof zr?{code:t.code||"UNKNOWN_ERROR",message:t.message||"Unknown error occurred",diagnosticsId:t.diagnosticsId,data:t.data}:(()=>{let s=t,l=s instanceof Error&&"code"in s&&typeof s.code=="string"?s.code:"UNKNOWN_ERROR",c=s instanceof Error?s.message:"Unknown error occurred";return{code:l,message:c,data:{error:t}}})();if(r.host.sdkStateController.setPaymentFailure(o),r.host.primerEventsController.dispatchPaymentFailure({code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},e,a),X({eventName:"PAYMENT_FAILURE",paymentId:a?.id,paymentMethod:e}),r.primerJS?.onPaymentFailure){let s=Math.floor(Date.now()/1e3);r.primerJS.onPaymentFailure({error:{code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},payment:a?ta(a):void 0,paymentMethodType:e,timestamp:s})}}var kn="1.0.2",jr=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 B(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()}),new B(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)&&X({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}normalizeOptionsForLegacySdk(t){if(t.sdkCore!==!1)return{...t,sdkCore:!0};let e={...t};if(e.card?.cardholderName){let a={...e.card.cardholderName};a.visible===!1&&(a.required=!1),e.card={...e.card,cardholderName:a}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkStateController.currentState.isLoading&&(P.warn("Loading timeout reached, resetting SDK state"),X({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkStateController.completeLoading())},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.paymentsList=[],this.createPaymentMethodManager=null,this.host.sdkStateController.reset(),this.currentSdkInstance.teardown?.(),P.info("SDK instance cleaned up")}catch(t){P.errorWithDatadog("Error cleaning up SDK instance",{error:t})}As(),P.setClientToken(void 0),P.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=qs){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){P.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await Qs(t),await e.Primer.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return P.warn("Component disconnected, aborting SDK initialization"),w;if(!t||!e)return w;this.cleanupResources();let a;try{let i;if(e.sdkCore!==!1){let l=new $r,c=na(e.locale||xr()),m=await tl(c);i={createHeadless:(h,T)=>rs(h,{...T,dialogProvider:l,translate:m,sdkVersion:kn,locale:c})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new Hr(null),this.primerJS.setVaultController(this.host.vaultManagerController);let n=this.normalizeOptionsForLegacySdk(e);P.setClientToken(t),P.setSdkOptions(n);let o=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:l=>{this.isDisconnected||(P.info("Configuration payment methods:",l),this.paymentsList=l)},onCheckoutComplete:({payment:l})=>{let c=l?.paymentMethodData?.paymentMethodType;rl({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,c)},onCheckoutFail:(l,c)=>{let m=c.payment?.paymentMethodData?.paymentMethodType;il({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,m,c.payment)},onBeforePaymentCreate:(l,c)=>{if(!l.paymentMethodType){P.error("Payment creation started without payment method type"),c?.abortPaymentCreation();return}if(!(al({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l.paymentMethodType,c)||this.isDisconnected)){if(this.primerJS?.onPaymentPrepare){this.primerJS.onPaymentPrepare({paymentMethodType:l.paymentMethodType},c);return}c?.continuePaymentCreation()}},onPaymentMethodAction:(l,c)=>{this.isDisconnected||l==="PAYMENT_METHOD_UNSELECTED"&&(this.host.primerEventsController.dispatchPaymentCancel(c),this.host.sdkStateController.stopProcessing())},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.createPaymentMethodManager=o.createPaymentMethodManager.bind(o),this.currentSdkInstance=o,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:o,writable:!1}),await o.start(),this.isDisconnected)return this.cleanupResources(),w;this.host.sdkContextController.setClientOptions(e),this.primerJS&&this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS);let s=o.getSDKUtilities();if(a=o.getAnalyticsUtils?.(),a&&(this.host.sdkContextController.setAnalyticsUtils({...a,sdkVersion:kn}),bs({environment:a.environment,checkoutSessionId:a.checkoutSessionId,clientSessionId:a.clientSessionId||"",primerAccountId:a.primerAccountId||"",sdkVersion:kn,clientSessionToken:a.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),a.configurationFetchStartTime&&ze.setSdkInitStartTime(a.configurationFetchStartTime),X({eventName:"SDK_INIT_START"})),this.host.sdkContextController.setHeadlessUtils(s),e.sdkCore&&o.getConfiguration){let l=o.getConfiguration();this.host.sdkContextController.setConfiguration(l)}return this.host.vaultManagerController.initializeVaultManager(o.createVaultManager.bind(o),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!s.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1}),o}catch(i){throw i instanceof Error&&(P.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkStateController.setPrimerJsError(i)),this.cleanupResources(),i}}}initializeLitContext(){return async([t,e])=>{if(this.isDisconnected)return w;if(!t||!e.length)return w;let a=new Map,i=new Map;try{for(let o of e){if(this.isDisconnected)break;let s=await this.initializePaymentMethodManager(o)();o&&s&&(a.set(o.type,o),i.set(o.type,s))}if(this.isDisconnected)return w;let n=Array.from(a.values());return this.host.sdkContextController.setPaymentManagers(i),this.host.sdkContextController.setPaymentMethods(n),this.primerJS&&(this.primerJS.setPaymentMethods(n),this.primerJS.setPaymentManagers(i)),this.host.primerEventsController.dispatchPaymentMethods(n),P.info("Initialized payment methods:",n),a}catch(n){if(n instanceof Error)throw this.host.sdkStateController.setPrimerJsError(n),n;return null}finally{this.clearLoadingTimeout(),this.isDisconnected||(this.host.sdkStateController.completeLoading(),X({eventName:"SDK_INIT_END"}))}}}initializePaymentMethodManager(t){let{type:e,managerType:a}=t;return async()=>{if(this.isDisconnected||!this.createPaymentMethodManager)return null;if(a==="KLARNA"){let i=await this.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:n=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:n,isLoading:!1})}});return i?{type:e,manager:i}:null}try{if(a==="CARD"){let n=await this.createPaymentMethodManager("PAYMENT_CARD",{onBinDataAvailable:o=>{this.isDisconnected||this.host.cardNetworkController.processBinDataAvailableEvent(o)},onCardNetworksChange:o=>{this.isDisconnected||this.host.cardNetworkController.processCardNetworkChangeEvent(o)},onCardNetworksLoading:()=>{this.isDisconnected||this.host.cardNetworkController.setCardNetworksLoading()},onBinDataLoadingChange:o=>{this.isDisconnected||this.host.primerEventsController.dispatchBinDataLoadingChange(o)}});return n?{type:e,manager:n}:null}let i=await this.createPaymentMethodManager(e);return i?{type:e,manager:i}:null}catch(i){return P.errorWithDatadog(`Failed to initialize manager for ${e}`,{error:i}),null}}}};var Wr=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 km=Wa({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});fn(r=>km(`../../localization/lit-localize/locales/${r}.ts`));var Lm={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},Ne=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=na(xr());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new br(this),this.sdkStateController=new Sr(this),this.primerEventsController=new aa(this),this.styleProcessingController=new Ar(this),this.vaultManagerController=new Ea(this),this.cardNetworkController=new Za(this),this.achPaymentEventsController=new Wr(this),this.headlessSdkController=new jr(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===Lm.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&&(bn(this.options?.locale)?this.locale=na(this.options?.locale):P.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),vn(this.locale))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}handleExternalCardSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:card-submit",e.detail)}handleExternalVaultSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:vault-submit",e.detail)}handleExternalShowOtherPaymentsToggle(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:show-other-payments-toggle",e.detail)}checkLoadingStateChange(){let e=this.sdkStateController?.currentState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,X({eventName:"CHECKOUT_FLOW_STARTED"});let a=ze.getSdkInitStartTime(),i=a?Date.now()-a:void 0;ds(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkStateController?.currentState.isLoading&&(P.warn("Loading timeout in component, forcing completion"),this.sdkStateController.forceCompleteLoading(),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkStateController.currentState,a=e.isLoading,i=e.primerJsError,n=!a&&!i;return p` ${R(a,()=>y)} ${R(i,()=>p`<primer-checkout-error></primer-checkout-error>`)} ${R(n,()=>p`<slot name="main" @slotchange=${this.onSlotChange}></slot>${R(this.hasAssignedContent,()=>y,()=>p`<primer-main></primer-main>`)} `,()=>y)} `}addEventListener(e,a,i){super.addEventListener(e,a,i)}removeEventListener(e,a,i){super.removeEventListener(e,a,i)}};Ne.styles=[I,Js],d([u({type:String,attribute:"custom-styles"})],Ne.prototype,"customStyles",2),d([u({type:String,attribute:"client-token"})],Ne.prototype,"clientToken",2),d([u({type:Object,attribute:!1,hasChanged:(e,a)=>!vr(e,a)})],Ne.prototype,"options",2),d([u({type:Boolean,attribute:"loader-disabled"})],Ne.prototype,"disableLoader",2),d([u({type:Boolean,reflect:!0,attribute:"js-initialized"})],Ne.prototype,"_jsInitialized",2),d([_e("slot")],Ne.prototype,"defaultSlot",2),d([N()],Ne.prototype,"previousLoadingState",2),Ne=d([D(),S("primer-checkout")],Ne);function Rm(r){return document.querySelector(`#${r}`)}function _m(r,t){let e=document.createElement("style");return e.textContent=r,e.id=t,e}function Ka(r,t,e=!0){if(!Yr||Rm(t))return;let i=_m(r,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var nl=`
|
|
146
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Vs=/'/g,Us=/"/g,$s=/^(?:script|style|textarea|title)$/i,Nn=r=>(t,...e)=>({_$litType$:r,strings:t,values:e}),p=Nn(1),Ke=Nn(2),Zv=Nn(3),Se=Symbol.for("lit-noChange"),y=Symbol.for("lit-nothing"),Hs=new WeakMap,Ft=Vt.createTreeWalker(Vt,129);function zs(r,t){if(!Pn(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Gs!==void 0?Gs.createHTML(t):t}var js=(r,t)=>{let e=r.length-1,a=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=_a;for(let s=0;s<e;s++){let l=r[s],c,m,g=-1,h=0;for(;h<l.length&&(o.lastIndex=h,m=o.exec(l),m!==null);)h=o.lastIndex,o===_a?m[1]==="!--"?o=Ks:m[1]!==void 0?o=Fs:m[2]!==void 0?($s.test(m[2])&&(i=RegExp("</"+m[2],"g")),o=Kt):m[3]!==void 0&&(o=Kt):o===Kt?m[0]===">"?(o=i??_a,g=-1):m[1]===void 0?g=-2:(g=o.lastIndex-m[2].length,c=m[1],o=m[3]===void 0?Kt:m[3]==='"'?Us:Vs):o===Us||o===Vs?o=Kt:o===Ks||o===Fs?o=_a:(o=Kt,i=void 0);let T=o===Kt&&r[s+1].startsWith("/>")?" ":"";n+=o===_a?l+Am:g>=0?(a.push(c),l.slice(0,g)+En+l.slice(g)+nt+T):l+nt+(g===-2?s:T)}return[zs(r,n+(r[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),a]},Oa=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]=js(t,e);if(this.el=r.createElement(c,a),Ft.currentNode=this.el.content,e===2||e===3){let g=this.el.content.firstChild;g.replaceWith(...g.childNodes)}for(;(i=Ft.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let g of i.getAttributeNames())if(g.endsWith(En)){let h=m[o++],T=i.getAttribute(g).split(nt),M=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:M[2],strings:T,ctor:M[1]==="."?Kr:M[1]==="?"?Fr:M[1]==="@"?Vr:Ht}),i.removeAttribute(g)}else g.startsWith(nt)&&(l.push({type:6,index:n}),i.removeAttribute(g));if($s.test(i.tagName)){let g=i.textContent.split(nt),h=g.length-1;if(h>0){i.textContent=Br?Br.emptyScript:"";for(let T=0;T<h;T++)i.append(g[T],wa()),Ft.nextNode(),l.push({type:2,index:++n});i.append(g[h],wa())}}}else if(i.nodeType===8)if(i.data===Tn)l.push({type:2,index:n});else{let g=-1;for(;(g=i.data.indexOf(nt,g+1))!==-1;)l.push({type:7,index:n}),g+=nt.length-1}n++}}static createElement(t,e){let a=Vt.createElement("template");return a.innerHTML=t,a}};function Ut(r,t,e=r,a){if(t===Se)return t;let i=a!==void 0?e._$Co?.[a]:e._$Cl,n=Da(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=Ut(r,i._$AS(r,t.values),i,a)),t}var Gr=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:a}=this._$AD,i=(t?.creationScope??Vt).importNode(e,!0);Ft.currentNode=i;let n=Ft.nextNode(),o=0,s=0,l=a[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new oa(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new Ur(n,this,t)),this._$AV.push(c),l=a[++s]}o!==l?.index&&(n=Ft.nextNode(),o++)}return Ft.currentNode=Vt,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++}},oa=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,a,i){this.type=2,this._$AH=y,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=a,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Ut(this,t,e),Da(t)?t===y||t==null||t===""?(this._$AH!==y&&this._$AR(),this._$AH=y):t!==this._$AH&&t!==Se&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ys(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==y&&Da(this._$AH)?this._$AA.nextSibling.data=t:this.T(Vt.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=Oa.createElement(zs(a.h,a.h[0]),this.options)),a);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new Gr(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=Hs.get(t.strings);return e===void 0&&Hs.set(t.strings,e=new Oa(t)),e}k(t){Pn(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(wa()),this.O(wa()),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))}},Ht=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,a,i,n){this.type=1,this._$AH=y,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,a.length>2||a[0]!==""||a[1]!==""?(this._$AH=Array(a.length-1).fill(new String),this.strings=a):this._$AH=y}_$AI(t,e=this,a,i){let n=this.strings,o=!1;if(n===void 0)t=Ut(this,t,e,0),o=!Da(t)||t!==this._$AH&&t!==Se,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ut(this,s[a+l],e,l),c===Se&&(c=this._$AH[l]),o||(o=!Da(c)||c!==this._$AH[l]),c===y?t=y:t!==y&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===y?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Kr=class extends Ht{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===y?void 0:t}},Fr=class extends Ht{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==y)}},Vr=class extends Ht{constructor(t,e,a,i,n){super(t,e,a,i,n),this.type=5}_$AI(t,e=this){if((t=Ut(this,t,e,0)??y)===Se)return;let a=this._$AH,i=t===y&&a!==y||t.capture!==a.capture||t.once!==a.once||t.passive!==a.passive,n=t!==y&&(a===y||i);i&&this.element.removeEventListener(this.name,this,a),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Ur=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){Ut(this,t)}},Ws={M:En,P:nt,A:Tn,C:1,L:js,R:Gr,D:Ys,V:Ut,I:oa,H:Ht,N:Fr,U:Vr,B:Kr,F:Ur},Cm=xa.litHtmlPolyfillSupport;Cm?.(Oa,oa),(xa.litHtmlVersions??(xa.litHtmlVersions=[])).push("3.3.0");var Zs=(r,t,e)=>{let a=e?.renderBefore??t,i=a._$litPart$;if(i===void 0){let n=e?.renderBefore??null;a._$litPart$=i=new oa(t.insertBefore(wa(),n),n,void 0,e??{})}return i._$AI(r),i};var Ba=globalThis,v=class extends it{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=Zs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Se}};v._$litElement$=!0,v.finalized=!0,Ba.litElementHydrateSupport?.({LitElement:v});var Mm=Ba.litElementPolyfillSupport;Mm?.({LitElement:v});(Ba.litElementVersions??(Ba.litElementVersions=[])).push("4.2.0");var S=r=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(r,t)})):customElements.define(r,t)};var Em={attribute:!0,type:String,converter:Ra,reflect:!1,hasChanged:Or},Tm=(r=Em,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"?Tm(r,t,e):((a,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,a),o?Object.getOwnPropertyDescriptor(i,n):void 0})(r,t,e)}function N(r){return u({...r,state:!0,attribute:!1})}var Yt=(r,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(r,t,e),e);function _e(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 Yt(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 Yt(e,a,{get(){return n(this)}})}}function R(r,t,e){return r?t(r):e?.(r)}var I=f` * { box-sizing: border-box; } `,Js=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 qs="https://sdk.primer.io/web/v2-latest/Primer.min.js",be="20px";var Hr=class{constructor(t){this.paymentMethods=null;this.paymentManagers=null;this.vaultController=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,a)=>this.startVaultPaymentInternal(e,a),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=t}setPaymentManagers(t){this.paymentManagers=t}setVaultController(t){this.vaultController=t}async createCvvInputInternal(t){return this.vaultController?this.vaultController.createCvvInput(t):(P.warn("PrimerJS: Vault not available - createCvvInput cannot be called"),null)}async startVaultPaymentInternal(t,e){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.startVaultPaymentById(t,e)}async deleteVaultPaymentMethod(t){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.deleteVaultedPaymentMethod(t)}async createCvvInput(t){return this.vault.createCvvInput(t)}async startVaultPayment(t,e){return this.vault.startPayment(t,e)}async refreshSession(){if(!this.headlessInstance){P.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw P.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods:(P.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let a=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:a})}}setCardholderName(t){if(!this.paymentManagers){P.warn("PrimerJS: Payment managers not available - setCardholderName cannot be called yet");return}let e=this.paymentManagers.get("PAYMENT_CARD");if(!e||e.type!=="PAYMENT_CARD"){P.warn("PrimerJS: Card payment manager not available");return}try{e.manager.setCardholderName(t)}catch(a){P.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:a})}}};var Yr=typeof window<"u"&&typeof window.document<"u";function Pm(r){return document.querySelector(`script[src^="${r}"]`)}function Nm(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 Qs(r,t=!1){if(!Yr)throw new Error("Cannot load script in server environment");let e=Pm(r)??Nm(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 Xs=f` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var oe=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.open=!1}openDialog(){this.open=!0}closeDialog(){let e=()=>{this.open=!1,this.removeEventListener("primer:dialog-close",e)};this.addEventListener("primer:dialog-close",e),this.dialog.startExitAnimation()}connectedCallback(){super.connectedCallback(),this.open||this.openDialog()}updated(e){super.updated(e),e.has("open")&&this.open&&this.onOpen&&this.onOpen(),e.has("open")&&this.open&&this.onContentRendered&&this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.onContentRendered?.()})})}render(){return this.open?p`<primer-dialog .open=${this.open} size=${this.size} .showCloseButton=${this.showCloseButton} @primer:dialog-close="${()=>{this.open=!1}}" ><slot></slot>${this.cta?p`<primer-button @click=${this.cta.onClick} class="cta-button">${this.cta.icon?p`<primer-icon name="${this.cta.icon}" size="sm" color="var(--primer-color-background-outlined-default)" ></primer-icon>`:y} ${this.cta.label}</primer-button>`:y}</primer-dialog>`:y}};oe.styles=[I,Xs],d([u({type:String})],oe.prototype,"size",2),d([u({type:Boolean})],oe.prototype,"showCloseButton",2),d([u({type:Object})],oe.prototype,"onOpen",2),d([u({type:Object})],oe.prototype,"onContentRendered",2),d([u({type:Object})],oe.prototype,"cta",2),d([N()],oe.prototype,"open",2),d([_e("primer-dialog")],oe.prototype,"dialog",2),oe=d([S("primer-portal-dialog"),D()],oe);var $r=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let a=new oe;a.size=t.size??"large",a.showCloseButton=t.showCloseButton??!1,a.onContentRendered=t.onContentReady,a.cta=t.cta;let i=()=>{a.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};a.addEventListener("primer:dialog-close",i),this.currentDialog=a,this.currentResolver=e,document.body.appendChild(a),a.appendChild(t.htmlContent)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}};var Im=Wa({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});var sa=null,In=null;async function el(r){if(In===r&&sa)return sa;try{return sa=(await Im(`../../../localization/lit-localize/locales/${r}.ts`)).templates,In=r,sa}catch{return r!=="en-GB"?el("en-GB"):(sa={},In=r,sa)}}async function tl(r){let t=await el(r);return(e,a)=>t[e]??a}var Ct={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"},Ga={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"};var zr=class r extends Error{constructor(t,e){super(e.message),this.name="PrimerClientError",this.code=t,this.diagnosticsId=e.diagnosticsId||null,this.data=e.data,this.isFromDeveloper=e.isFromDeveloper||!1}static fromErrorCode(t,e){return new r(t,e)}};function al(r,t,e){return r.isDisconnected?!1:(r.host.sdkStateController.currentState.paymentFailure!==null&&X({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),r.host.sdkStateController.startProcessing(),r.host.primerEventsController.dispatchPaymentStart(t,e))}function rl(r,t,e){if(!r.isDisconnected&&(P.info("Payment completed:",t),r.host.sdkStateController.completeProcessing(),r.host.primerEventsController.dispatchPaymentSuccess(t,e),X({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),r.primerJS?.onPaymentSuccess)){let a=Math.floor(Date.now()/1e3);r.primerJS.onPaymentSuccess({payment:ta(t),paymentMethodType:e,timestamp:a})}}function il(r,t,e,a){if(r.isDisconnected)return;(s=>typeof s=="object"&&s!==null&&"response"in s&&typeof s.response=="object"&&s.response!==null&&"status"in s.response&&typeof s.response.status=="number")(t)&&t.response.status>=500?P.errorWithDatadog("Payment failed with server error",{error:t}):P.error("Payment failed:",t);let o=t instanceof zr?{code:t.code||"UNKNOWN_ERROR",message:t.message||"Unknown error occurred",diagnosticsId:t.diagnosticsId,data:t.data}:(()=>{let s=t,l=s instanceof Error&&"code"in s&&typeof s.code=="string"?s.code:"UNKNOWN_ERROR",c=s instanceof Error?s.message:"Unknown error occurred";return{code:l,message:c,data:{error:t}}})();if(r.host.sdkStateController.setPaymentFailure(o),r.host.primerEventsController.dispatchPaymentFailure({code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},e,a),X({eventName:"PAYMENT_FAILURE",paymentId:a?.id,paymentMethod:e}),r.primerJS?.onPaymentFailure){let s=Math.floor(Date.now()/1e3);r.primerJS.onPaymentFailure({error:{code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},payment:a?ta(a):void 0,paymentMethodType:e,timestamp:s})}}var kn="1.0.4",jr=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 B(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()}),new B(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)&&X({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}normalizeOptionsForLegacySdk(t){if(t.sdkCore!==!1)return{...t,sdkCore:!0};let e={...t};if(e.card?.cardholderName){let a={...e.card.cardholderName};a.visible===!1&&(a.required=!1),e.card={...e.card,cardholderName:a}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkStateController.currentState.isLoading&&(P.warn("Loading timeout reached, resetting SDK state"),X({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkStateController.completeLoading())},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.paymentsList=[],this.createPaymentMethodManager=null,this.host.sdkStateController.reset(),this.currentSdkInstance.teardown?.(),P.info("SDK instance cleaned up")}catch(t){P.errorWithDatadog("Error cleaning up SDK instance",{error:t})}As(),P.setClientToken(void 0),P.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=qs){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){P.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await Qs(t),await e.Primer.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return P.warn("Component disconnected, aborting SDK initialization"),w;if(!t||!e)return w;this.cleanupResources();let a;try{let i;if(e.sdkCore!==!1){let l=new $r,c=na(e.locale||xr()),m=await tl(c);i={createHeadless:(h,T)=>rs(h,{...T,dialogProvider:l,translate:m,sdkVersion:kn,locale:c})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new Hr(null),this.primerJS.setVaultController(this.host.vaultManagerController);let n=this.normalizeOptionsForLegacySdk(e);P.setClientToken(t),P.setSdkOptions(n);let o=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:l=>{this.isDisconnected||(P.info("Configuration payment methods:",l),this.paymentsList=l)},onCheckoutComplete:({payment:l})=>{let c=l?.paymentMethodData?.paymentMethodType;rl({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,c)},onCheckoutFail:(l,c)=>{let m=c.payment?.paymentMethodData?.paymentMethodType;il({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,m,c.payment)},onBeforePaymentCreate:(l,c)=>{if(!l.paymentMethodType){P.error("Payment creation started without payment method type"),c?.abortPaymentCreation();return}if(!(al({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l.paymentMethodType,c)||this.isDisconnected)){if(this.primerJS?.onPaymentPrepare){this.primerJS.onPaymentPrepare({paymentMethodType:l.paymentMethodType},c);return}c?.continuePaymentCreation()}},onPaymentMethodAction:(l,c)=>{this.isDisconnected||l==="PAYMENT_METHOD_UNSELECTED"&&(this.host.primerEventsController.dispatchPaymentCancel(c),this.host.sdkStateController.stopProcessing())},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.createPaymentMethodManager=o.createPaymentMethodManager.bind(o),this.currentSdkInstance=o,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:o,writable:!1}),await o.start(),this.isDisconnected)return this.cleanupResources(),w;this.host.sdkContextController.setClientOptions(e),this.primerJS&&this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS);let s=o.getSDKUtilities();if(a=o.getAnalyticsUtils?.(),a&&(this.host.sdkContextController.setAnalyticsUtils({...a,sdkVersion:kn}),bs({environment:a.environment,checkoutSessionId:a.checkoutSessionId,clientSessionId:a.clientSessionId||"",primerAccountId:a.primerAccountId||"",sdkVersion:kn,clientSessionToken:a.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),a.configurationFetchStartTime&&ze.setSdkInitStartTime(a.configurationFetchStartTime),X({eventName:"SDK_INIT_START"})),this.host.sdkContextController.setHeadlessUtils(s),e.sdkCore&&o.getConfiguration){let l=o.getConfiguration();this.host.sdkContextController.setConfiguration(l)}return this.host.vaultManagerController.initializeVaultManager(o.createVaultManager.bind(o),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!s.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1}),o}catch(i){throw i instanceof Error&&(P.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkStateController.setPrimerJsError(i)),this.cleanupResources(),i}}}initializeLitContext(){return async([t,e])=>{if(this.isDisconnected)return w;if(!t||!e.length)return w;let a=new Map,i=new Map;try{for(let o of e){if(this.isDisconnected)break;let s=await this.initializePaymentMethodManager(o)();o&&s&&(a.set(o.type,o),i.set(o.type,s))}if(this.isDisconnected)return w;let n=Array.from(a.values());return this.host.sdkContextController.setPaymentManagers(i),this.host.sdkContextController.setPaymentMethods(n),this.primerJS&&(this.primerJS.setPaymentMethods(n),this.primerJS.setPaymentManagers(i)),this.host.primerEventsController.dispatchPaymentMethods(n),P.info("Initialized payment methods:",n),a}catch(n){if(n instanceof Error)throw this.host.sdkStateController.setPrimerJsError(n),n;return null}finally{this.clearLoadingTimeout(),this.isDisconnected||(this.host.sdkStateController.completeLoading(),X({eventName:"SDK_INIT_END"}))}}}initializePaymentMethodManager(t){let{type:e,managerType:a}=t;return async()=>{if(this.isDisconnected||!this.createPaymentMethodManager)return null;if(a==="KLARNA"){let i=await this.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:n=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:n,isLoading:!1})}});return i?{type:e,manager:i}:null}try{if(a==="CARD"){let n=await this.createPaymentMethodManager("PAYMENT_CARD",{onBinDataAvailable:o=>{this.isDisconnected||this.host.cardNetworkController.processBinDataAvailableEvent(o)},onCardNetworksChange:o=>{this.isDisconnected||this.host.cardNetworkController.processCardNetworkChangeEvent(o)},onCardNetworksLoading:()=>{this.isDisconnected||this.host.cardNetworkController.setCardNetworksLoading()},onBinDataLoadingChange:o=>{this.isDisconnected||this.host.primerEventsController.dispatchBinDataLoadingChange(o)}});return n?{type:e,manager:n}:null}let i=await this.createPaymentMethodManager(e);return i?{type:e,manager:i}:null}catch(i){return P.errorWithDatadog(`Failed to initialize manager for ${e}`,{error:i}),null}}}};var Wr=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 km=Wa({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});fn(r=>km(`../../localization/lit-localize/locales/${r}.ts`));var Lm={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},Ne=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=na(xr());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new br(this),this.sdkStateController=new Sr(this),this.primerEventsController=new aa(this),this.styleProcessingController=new Ar(this),this.vaultManagerController=new Ea(this),this.cardNetworkController=new Za(this),this.achPaymentEventsController=new Wr(this),this.headlessSdkController=new jr(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===Lm.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&&(bn(this.options?.locale)?this.locale=na(this.options?.locale):P.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),vn(this.locale))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}handleExternalCardSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:card-submit",e.detail)}handleExternalVaultSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:vault-submit",e.detail)}handleExternalShowOtherPaymentsToggle(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:show-other-payments-toggle",e.detail)}checkLoadingStateChange(){let e=this.sdkStateController?.currentState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,X({eventName:"CHECKOUT_FLOW_STARTED"});let a=ze.getSdkInitStartTime(),i=a?Date.now()-a:void 0;ds(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkStateController?.currentState.isLoading&&(P.warn("Loading timeout in component, forcing completion"),this.sdkStateController.forceCompleteLoading(),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkStateController.currentState,a=e.isLoading,i=e.primerJsError,n=!a&&!i;return p` ${R(a,()=>y)} ${R(i,()=>p`<primer-checkout-error></primer-checkout-error>`)} ${R(n,()=>p`<slot name="main" @slotchange=${this.onSlotChange}></slot>${R(this.hasAssignedContent,()=>y,()=>p`<primer-main></primer-main>`)} `,()=>y)} `}addEventListener(e,a,i){super.addEventListener(e,a,i)}removeEventListener(e,a,i){super.removeEventListener(e,a,i)}};Ne.styles=[I,Js],d([u({type:String,attribute:"custom-styles"})],Ne.prototype,"customStyles",2),d([u({type:String,attribute:"client-token"})],Ne.prototype,"clientToken",2),d([u({type:Object,attribute:!1,hasChanged:(e,a)=>!vr(e,a)})],Ne.prototype,"options",2),d([u({type:Boolean,attribute:"loader-disabled"})],Ne.prototype,"disableLoader",2),d([u({type:Boolean,reflect:!0,attribute:"js-initialized"})],Ne.prototype,"_jsInitialized",2),d([_e("slot")],Ne.prototype,"defaultSlot",2),d([N()],Ne.prototype,"previousLoadingState",2),Ne=d([D(),S("primer-checkout")],Ne);function Rm(r){return document.querySelector(`#${r}`)}function _m(r,t){let e=document.createElement("style");return e.textContent=r,e.id=t,e}function Ka(r,t,e=!0){if(!Yr||Rm(t))return;let i=_m(r,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var nl=`
|
|
147
147
|
@keyframes primer-css-spinner-rotate {
|
|
148
148
|
0% {
|
|
149
149
|
transform: rotate(0deg);
|
|
@@ -153,7 +153,9 @@ import{a as Wa,b as q,c as Pi,d,e as k}from"./chunks/chunk.QNO3CTH5.js";var ac=q
|
|
|
153
153
|
}
|
|
154
154
|
}
|
|
155
155
|
|
|
156
|
-
primer-
|
|
156
|
+
/* Hide primer-main while primer components are loading to prevent FOUC
|
|
157
|
+
Only check for undefined primer-* elements, ignoring browser extensions */
|
|
158
|
+
primer-checkout:has(primer-main:not(:defined), primer-checkout-error:not(:defined)) > * {
|
|
157
159
|
visibility: hidden;
|
|
158
160
|
}
|
|
159
161
|
|
package/dist/web-types.json
CHANGED
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": "1.0.
|
|
5
|
+
"version": "1.0.4",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "./dist/primer-loader.js",
|
|
8
8
|
"types": "./dist/primer-loader.d.ts",
|