@bigcommerce/checkout-sdk 1.857.0 → 1.858.0

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.
@@ -1,2 +1,2 @@
1
- import{getScriptLoader as e}from"@bigcommerce/script-loader";import{find as t,isEmpty as i,isEqual as n,isNil as r,noop as o,omit as a,omitBy as s,some as d}from"lodash";import{supportsPopups as l}from"@braintree/browser-detection";import{createRequestSender as c}from"@bigcommerce/request-sender";import{createFormPoster as u}from"@bigcommerce/form-poster";var h,y,m;class p extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class g extends p{constructor(e){super(e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}!function(e){e.Sandbox="sandbox",e.Production="production"}(h||(h={})),function(e){e.Client="client",e.DataCollector="dataCollector",e.Fastlane="fastlane",e.GooglePayment="googlePayment",e.HostedFields="hostedFields",e.LocalPayment="localPayment",e.Paypal="paypal",e.PaypalCheckout="paypalCheckout",e.ThreeDSecure="threeDSecure",e.UsBankAccount="usBankAccount",e.Venmo="venmo",e.VisaCheckout="visaCheckout"}(y||(y={})),function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(m||(m={}));const v="3.128.0",f="3.123.2",b="3.106.0",w={[b]:{[y.Client]:"sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt",[y.PaypalCheckout]:"sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O",[y.Paypal]:"sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+",[y.LocalPayment]:"sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT",[y.DataCollector]:"sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV",[y.UsBankAccount]:"sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ",[y.GooglePayment]:"sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe",[y.ThreeDSecure]:"sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB",[y.VisaCheckout]:"sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT",[y.Venmo]:"sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov",[y.HostedFields]:"sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy",[y.Fastlane]:"sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa"},[f]:{[y.Client]:"sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO",[y.PaypalCheckout]:"sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/",[y.Paypal]:"sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt",[y.LocalPayment]:"sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH",[y.DataCollector]:"sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO",[y.UsBankAccount]:"sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW",[y.GooglePayment]:"sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO",[y.ThreeDSecure]:"sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym",[y.VisaCheckout]:"sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS",[y.Venmo]:"sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU",[y.HostedFields]:"sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P",[y.Fastlane]:"sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y"},[v]:{[y.Client]:"sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq",[y.PaypalCheckout]:"sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh",[y.Paypal]:"sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH",[y.LocalPayment]:"sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC",[y.DataCollector]:"sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc",[y.UsBankAccount]:"sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F",[y.GooglePayment]:"sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i",[y.ThreeDSecure]:"sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D",[y.VisaCheckout]:"sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv",[y.Venmo]:"sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz",[y.HostedFields]:"sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z",[y.Fastlane]:"sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr"}};var C,S,P,I,O,k,E,T,A=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class z{constructor(e,t,i){this.scriptLoader=e,this.braintreeHostWindow=t,this.braintreeSDKVersionManager=i}loadClient(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.Client,"client.min.js")})}loadFastlane(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.Fastlane,"fastlane.min.js")})}loadPaypalCheckout(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.PaypalCheckout,"paypal-checkout.min.js")})}loadPaypal(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.Paypal,"paypal.min.js")})}loadLocalPayment(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.LocalPayment,"local-payment.min.js")})}loadDataCollector(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.DataCollector,"data-collector.min.js")})}loadUsBankAccount(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.UsBankAccount,"us-bank-account.min.js")})}loadGooglePayment(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.GooglePayment,"google-payment.min.js")})}load3DS(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.ThreeDSecure,"three-d-secure.min.js")})}loadVisaCheckout(){return this.loadBraintreeModuleOrThrow(y.VisaCheckout,"visa-checkout.min.js")}loadVenmoCheckout(){return this.loadBraintreeModuleOrThrow(y.Venmo,"venmo.min.js")}loadHostedFields(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.HostedFields,"hosted-fields.min.js")})}loadVisaCheckoutSdk(e){return A(this,void 0,void 0,function*(){if(this.braintreeHostWindow.V)return this.braintreeHostWindow.V;const t=e?"sha384-0eu1s1GtqzXlL9DtLgmwzC5WWlEH/ADRM0n38cVQkvtT+W/gey96rcb1LwuUOPDm":"sha384-1f1csvP3ZFxg4dILH1GaY4LHlZ0oX7Rk83rxmLlwbnIi4TM0NYzXoev1VoEiVDS6";return this.scriptLoader.loadScript(`//${e?"sandbox-":""}assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,{async:!0,attributes:{integrity:t,crossorigin:"anonymous"}}).then(()=>{if(!this.braintreeHostWindow.V)throw new g;return this.braintreeHostWindow.V})})}loadBraintreeModuleOrThrow(e,t){return A(this,void 0,void 0,function*(){let i=this.getBraintreeModule(e);if(i)return i;const n=this.braintreeSDKVersionManager.getSDKVersion(),r=`//js.braintreegateway.com/web/${n}/js/${t}`,o=n in w?this.getIntegrityValuesByModuleName(e,n):void 0;if(yield this.scriptLoader.loadScript(r,o?{async:!0,attributes:{integrity:o,crossorigin:"anonymous"}}:void 0),i=this.getBraintreeModule(e),!i)throw new g;return i})}getBraintreeModule(e){var t;return null===(t=this.braintreeHostWindow.braintree)||void 0===t?void 0:t[e]}getIntegrityValuesByModuleName(e,t){const i=w[t][e];if(!i)throw new Error("Unexpected fileName value");return i}}class N extends p{constructor(e){super(e||"Unsupported browser error"),this.name="UnsupportedBrowserError",this.type="unsupported_browser"}}!function(e){e[e.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",e[e.CustomerNotInitialized=1]="CustomerNotInitialized",e[e.PaymentNotInitialized=2]="PaymentNotInitialized",e[e.ShippingNotInitialized=3]="ShippingNotInitialized",e[e.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(C||(C={}));class M extends p{constructor(e){super(function(e){switch(e){case C.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case C.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case C.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case C.SpamProtectionNotInitialized:return"Unable to proceed because the checkout spam protection has not been initialized.";default:return"Unable to proceed because the required component has not been initialized."}}(e)),this.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}function D(e){return Boolean("object"==typeof e&&null!==e&&("type"in e||"message"in e||"code"in e))}!function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(S||(S={})),function(e){e.Completed="COMPLETED",e.Pending="PENDING",e.Failed="FAILED"}(P||(P={})),function(e){e.TRUSTLY="trustly"}(I||(I={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="cancelled",e.UNRECOGNIZED="unrecognized"}(O||(O={})),function(e){e.Customer="CUSTOMER",e.Merchant="MERCHANT",e.Network="NETWORK",e.Internal="INTERNAL",e.Unknown="UNKNOWN"}(k||(k={})),function(e){e.KountNotEnabled="DATA_COLLECTOR_KOUNT_NOT_ENABLED"}(E||(E={})),function(e){e.Visa="visa",e.Mastercard="mastercard",e.AmericanExpress="american-express",e.DinersClub="diners-club",e.Discover="discover",e.Jcb="jcb",e.UnionPay="union-pay",e.Maestro="maestro",e.Elo="elo",e.Mir="mir",e.Hiper="hiper",e.Hipercard="hipercard"}(T||(T={}));var _=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class B{constructor(e){this.braintreeScriptLoader=e}initialize(e){this.setClientToken(e)}deinitialize(){return _(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollector),this.dataCollector=void 0})}getClient(){return _(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=yield t.create({authorization:e})}return this.client})}getDataCollectorOrThrow(e){return _(this,void 0,void 0,function*(){const t={deviceData:void 0,teardown:()=>Promise.resolve()};if(!this.dataCollector)try{const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadDataCollector(),n=Object.assign({client:t,kount:!0},e);this.dataCollector=yield i.create(n)}catch(e){if(D(e)&&e.code===E.KountNotEnabled)return t;throw e}return this.dataCollector})}getBraintreeGooglePayment(){return _(this,void 0,void 0,function*(){if(!this.googlePayment){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadGooglePayment()]);this.googlePayment=yield t.create({client:e})}return this.googlePayment})}getBraintreeThreeDS(){return _(this,void 0,void 0,function*(){if(!this.threeDS){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]);this.threeDS=yield t.create({client:e,version:2})}return this.threeDS})}getBraintreeLocalPayment(e){return _(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment){const[t,i]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadLocalPayment()]);this.braintreeLocalPayment=yield new Promise((n,r)=>{i.create({client:t,merchantAccountId:e},(e,t)=>{e&&r(e),n(t)})})}return this.braintreeLocalPayment})}getUsBankAccount(){return _(this,void 0,void 0,function*(){if(!this.usBankAccount){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadUsBankAccount();this.usBankAccount=yield t.create({client:e})}return this.usBankAccount})}getBraintreeVisaCheckout(){return this.visaCheckout||(this.visaCheckout=Promise.all([this.getClient(),this.braintreeScriptLoader.loadVisaCheckout()]).then(([e,t])=>t.create({client:e}))),this.visaCheckout}getVisaCheckoutSdk(e){return _(this,void 0,void 0,function*(){return this.visaCheckoutSDK||(this.visaCheckoutSDK=yield this.braintreeScriptLoader.loadVisaCheckoutSdk(e)),this.visaCheckoutSDK})}getVenmoCheckoutOrThrow(){return _(this,void 0,void 0,function*(){if(!this.braintreeVenmo){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadVenmoCheckout(),i={client:e,allowDesktop:!0,paymentMethodUsage:"multi_use"},n=yield t.create(i);if(!n.isBrowserSupported())throw new N;this.braintreeVenmo=n}return this.braintreeVenmo})}setClientToken(e){this.clientToken=e}getClientTokenOrThrow(){if(!this.clientToken)throw new M(C.PaymentNotInitialized);return this.clientToken}teardownModule(e){return e?e.teardown():Promise.resolve()}}function x(e,t,i=!0){var n;return null!==(n=e[t])&&void 0!==n?n:i}class F{constructor(e){this.paymentIntegrationService=e,this.braintreeWindow=window}getSDKVersion(){const e=this.paymentIntegrationService.getState().getStoreConfig(),t=(null==e?void 0:e.checkoutSettings.features)||{};return this.getPreloadedSDKVersion()||(x(t,"PAYPAL-5809.braintree_hosted_fields_fix_version")?v:x(t,"PAYPAL-5636.update_braintree_sdk_version")?f:b)}getPreloadedSDKVersion(){const e=this.braintreeWindow.braintree;if(e){const i=t(Object.values(e),e=>!!e.VERSION);return null==i?void 0:i.VERSION}}}function L(e,t){return Object.assign(e,{resolveIds:t})}class V extends p{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}var j;!function(e){e[e.MissingBillingAddress=0]="MissingBillingAddress",e[e.MissingCart=1]="MissingCart",e[e.MissingCheckout=2]="MissingCheckout",e[e.MissingConsignments=3]="MissingConsignments",e[e.MissingCustomer=4]="MissingCustomer",e[e.MissingCheckoutConfig=5]="MissingCheckoutConfig",e[e.MissingOrder=6]="MissingOrder",e[e.MissingOrderConfig=7]="MissingOrderConfig",e[e.MissingOrderId=8]="MissingOrderId",e[e.MissingPayment=9]="MissingPayment",e[e.MissingPaymentId=10]="MissingPaymentId",e[e.MissingPaymentInstrument=11]="MissingPaymentInstrument",e[e.MissingPaymentMethod=12]="MissingPaymentMethod",e[e.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=14]="MissingPaymentStatus",e[e.MissingPaymentToken=15]="MissingPaymentToken",e[e.MissingShippingAddress=16]="MissingShippingAddress"}(j||(j={}));class U extends p{constructor(e){super(function(e){switch(e){case j.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case j.MissingCart:return"Unable to proceed because cart data is unavailable.";case j.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case j.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case j.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case j.MissingCheckoutConfig:case j.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case j.MissingOrder:return"Unable to proceed because order data is unavailable.";case j.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case j.MissingPayment:return"Unable to proceed because payment data is unavailable.";case j.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case j.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case j.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e)),this.subtype=e,this.name="MissingDataError",this.type="missing_data"}}class R extends V{constructor(e){let t="Unable to submit payment for the order because the payload is invalid.";e&&(t=`${t} Make sure the following fields are provided correctly: ${e.join(", ")}.`),super(t),this.name="PaymentArgumentInvalidError"}}function H(e){return Boolean(e.instrumentId)}class W extends p{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}function q(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}class $ extends p{constructor(e){super(e||"Unable to proceed because the client library of a payment method has thrown an unexpected error."),this.name="PaymentMethodFailedError",this.type="payment_method_client_invalid"}}function G(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var Y=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class J{constructor(e,t){this.paymentIntegrationService=e,this.braintreeSdk=t}initialize(e){return Y(this,void 0,void 0,function*(){const{methodId:t,braintreeach:i}=e||{};if(!t)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');this.getMandateText=null==i?void 0:i.getMandateText,yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{clientToken:r,initializationData:o}=n;if(!r||!o)throw new U(j.MissingPaymentMethod);this.braintreeSdk.initialize(r);try{this.usBankAccount=yield this.braintreeSdk.getUsBankAccount()}catch(e){this.handleBraintreeError(e)}})}execute(e,t){return Y(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new R(["payment"]);const r=H(i.paymentData||{}),o=r?yield this.tokenizePaymentForVaultedInstrument(i):yield this.tokenizePayment(i),a=r?yield this.preparePaymentDataForVaultedInstrument(o,i):yield this.preparePaymentData(o,i);yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new W)}deinitialize(){return Y(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}tokenizePayment({paymentData:e}){return Y(this,void 0,void 0,function*(){const t=this.getUsBankAccountOrThrow();if(!G(e))throw new R(["payment.paymentData"]);const i=H(e)?"The data are used for stored instrument verification":"function"==typeof this.getMandateText&&this.getMandateText();if(!i)throw new V("Unable to proceed because getMandateText is not provided or returned undefined value.");try{const{nonce:n}=yield t.tokenize({bankDetails:this.getBankDetails(e),mandateText:i});return n}catch(e){this.handleBraintreeError(e)}})}tokenizePaymentForVaultedInstrument(e){return Y(this,void 0,void 0,function*(){const{methodId:t,paymentData:i={}}=e,n=this.paymentIntegrationService.getState(),{config:r}=n.getPaymentMethodOrThrow(t);if(!r.isVaultingEnabled)throw new V("Vaulting is disabled but a vaulted instrument was being used for this transaction");return G(i)?this.tokenizePayment(e):null})}preparePaymentData(e,t){return Y(this,void 0,void 0,function*(){const{methodId:i,paymentData:n={}}=t;if(!G(n))throw new R(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,routingNumber:s,accountNumber:d}=n;return{methodId:i,paymentData:{deviceSessionId:r,shouldSetAsDefaultInstrument:a,shouldSaveInstrument:o,formattedPayload:{tokenized_bank_account:{issuer:s,masked_account_number:d.substr(-4),token:e}}}}})}preparePaymentDataForVaultedInstrument(e,t){return Y(this,void 0,void 0,function*(){const{methodId:i,paymentData:n={}}=t;if(!H(n)||!q(n))throw new R(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{instrumentId:o,shouldSetAsDefaultInstrument:a}=n;return{methodId:i,paymentData:Object.assign({deviceSessionId:r,instrumentId:o,shouldSetAsDefaultInstrument:a},e&&{nonce:e})}})}getBankDetails(e){const t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i=e.ownershipType.toLowerCase(),n=e.accountType.toLowerCase();return Object.assign(Object.assign({accountNumber:e.accountNumber,routingNumber:e.routingNumber,ownershipType:i},"personal"===i?{firstName:e.firstName,lastName:e.lastName}:{businessName:e.businessName}),{accountType:n,billingAddress:{streetAddress:t.address1,extendedAddress:t.address2,locality:t.city,region:t.stateOrProvinceCode,postalCode:t.postalCode}})}getUsBankAccountOrThrow(){if(!this.usBankAccount)throw new M(C.PaymentNotInitialized);return this.usBankAccount}handleBraintreeError(e){if(!D(e))throw e;throw new $(e.message)}}const K=L(t=>new J(t,(t=>{const i=new F(t),n=new z(e(),window,i);return new B(n)})(t)),[{id:"braintreeach"}]);class X extends p{constructor(e,t){super(t||"Unable to proceed because the payment form contains invalid data."),this.details=e,this.name="PaymentInvalidFormError",this.type="payment_invalid_form"}}class Q extends p{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}class Z{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}let ee=null;const te=["buttons","messages"];var ie,ne,re,oe,ae,se;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(ie||(ie={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(ne||(ne={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(re||(re={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(oe||(oe={})),function(e){e.PILL="pill",e.RECT="rect"}(ae||(ae={})),function(e){e.CART="cart",e.HOME="homepage",e.PAYMENT="payment",e.PRODUCT="product"}(se||(se={}));var de=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class le{constructor(e,t,i){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.overlay=i,this.dataCollectors={}}initialize(e,t){this.clientToken=e,this.threeDSecureOptions=t}getBraintreeFastlane(e,t,i){return de(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("axoEnv","sandbox"),window.localStorage.setItem("fastlaneEnv","sandbox")),!this.braintreeHostWindow.braintreeFastlane){const t=this.getClientTokenOrThrow(),n=yield this.getClient(),r=yield this.getSessionId(e),o=yield this.braintreeScriptLoader.loadFastlane(),a={root:{backgroundColorPrimary:"transparent"}};this.braintreeHostWindow.braintreeFastlane=yield o.create({authorization:t,client:n,deviceData:r,styles:i||a})}return this.braintreeHostWindow.braintreeFastlane})}getClient(){return de(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=t.create({authorization:e})}return this.client})}getPaypal(){return this.braintreePaypal||(this.braintreePaypal=Promise.all([this.getClient(),this.braintreeScriptLoader.loadPaypal()]).then(([e,t])=>t.create({client:e}))),this.braintreePaypal}paypal(e){var{shouldSaveInstrument:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["shouldSaveInstrument"]);const n=l();return this.getPaypal().then(e=>{var r;return n&&(null===(r=this.overlay)||void 0===r||r.show({onClick:()=>e.focusWindow()})),e.tokenize(Object.assign({enableShippingAddress:!0,flow:t?"vault":"checkout",useraction:"commit"},i))}).then(e=>{var t;return null===(t=this.overlay)||void 0===t||t.remove(),e}).catch(e=>{var t;throw null===(t=this.overlay)||void 0===t||t.remove(),e})}getPaypalCheckout(e,t,i){return de(this,void 0,void 0,function*(){const n=yield this.getClient(),r=yield this.braintreeScriptLoader.loadPaypalCheckout(),o={client:n};return this.paypalCheckout=yield r.create(o,(n,r)=>{var o;if(n)return i(n);const a=Object.assign(Object.assign({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:te.toString(),intent:e.intent,commit:null===(o=e.commit)||void 0===o||o});this.braintreeHostWindow.paypal?t(r):function(e,t){return ee||(ee=new Promise((i,n)=>{e.loadPayPalSDK(t,t=>{t?(ee=null,n(t)):i(e)})})),ee}(r,a).then(()=>t(r))}),this.paypalCheckout})}getDataCollector(e){return de(this,void 0,void 0,function*(){const t=(null==e?void 0:e.paypal)?"paypal":"default";let i=this.dataCollectors[t];if(!i){try{const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadDataCollector(),r=Object.assign({client:t,kount:!0},e);i=yield n.create(r)}catch(e){if(!D(e)||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==e.code)throw e;i={deviceData:void 0,teardown:()=>Promise.resolve()}}this.dataCollectors[t]=i}return i})}getBraintreeEnv(e=!1){return e?h.Sandbox:h.Production}mapToBraintreeShippingAddressOverride(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}mapToLegacyShippingAddress(e){const{email:t,phone:i,shippingAddress:n}=e,r=(null==n?void 0:n.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:i,address_line_1:null==n?void 0:n.line1,address_line_2:null==n?void 0:n.line2,city:null==n?void 0:n.city,state:null==n?void 0:n.state,country_code:null==n?void 0:n.countryCode,postal_code:null==n?void 0:n.postalCode}}mapToLegacyBillingAddress(e){const{billingAddress:t,email:i,firstName:n,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:i,first_name:n,last_name:r,phone_number:o,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}getSessionId(e){return de(this,void 0,void 0,function*(){const{deviceData:t}=yield this.getDataCollector({riskCorrelationId:e});return t})}teardown(){return de(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollectors.default),yield this.teardownModule(this.dataCollectors.paypal),this.dataCollectors={},yield this.teardownModule(this.paypalCheckout),this.paypalCheckout=void 0})}get3DS(){return de(this,void 0,void 0,function*(){return this.threeDS||(this.threeDS=Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]).then(([e,t])=>t.create({client:e,version:2}))),this.threeDS})}getVenmoCheckout(e){return de(this,void 0,void 0,function*(){if(!this.venmoCheckout){const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadVenmoCheckout(),n=Object.assign({client:t,allowDesktop:!0,paymentMethodUsage:"multi_use"},e||{});this.venmoCheckout=yield new Promise((e,t)=>{i.create(n,(i,n)=>i?t(i):n.isBrowserSupported()?void e(n):t(new N))})}return this.venmoCheckout})}verifyCard(e,t,i){return de(this,void 0,void 0,function*(){const n=yield this.tokenizeCard(e,t);return this.challenge3DSVerification(n,i)})}tokenizeCard(e,t){return de(this,void 0,void 0,function*(){const{paymentData:n}=e;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"object"==typeof t.ccExpiry&&null!==t.ccExpiry&&"string"==typeof t.ccNumber&&"string"==typeof t.ccName}(n))throw new R(["payment.paymentData"]);const r=this.getErrorsRequiredFields(n);if(!i(r))throw new X(r);const o=this.mapToCreditCard(n,t),a=yield this.getClient(),{creditCards:s}=yield a.request(o);return{nonce:s[0].nonce,bin:s[0].details.bin}})}challenge3DSVerification(e,t){return de(this,void 0,void 0,function*(){const i=yield this.get3DS();return this.present3DSChallenge(i,t,e)})}teardownModule(e){return e?e.teardown():Promise.resolve()}getClientTokenOrThrow(){if(!this.clientToken)throw new M(C.PaymentNotInitialized);return this.clientToken}getErrorsRequiredFields(e){const{ccNumber:t,ccExpiry:i}=e,n={};return t||(n.ccNumber=[{message:"Credit card number is required",type:"required"}]),i||(n.ccExpiry=[{message:"Expiration date is required",type:"required"}]),n}mapToCreditCard(e,t){return{data:{creditCard:{cardholderName:e.ccName,number:e.ccNumber,cvv:e.ccCvv,expirationDate:`${e.ccExpiry.month}/${e.ccExpiry.year}`,options:{validate:!1},billingAddress:t&&{countryCodeAlpha2:t.countryCode,locality:t.city,countryName:t.country,postalCode:t.postalCode,streetAddress:t.address2?`${t.address1} ${t.address2}`:t.address1}}},endpoint:"payment_methods/credit_cards",method:"post"}}present3DSChallenge(e,t,i){const{nonce:n,bin:r}=i;if(!this.threeDSecureOptions||!n)throw new M(C.PaymentNotInitialized);const{addFrame:o,removeFrame:a,challengeRequested:s=!0,additionalInformation:d}=this.threeDSecureOptions,l=()=>de(this,void 0,void 0,function*(){const t=yield e.cancelVerifyCard();return u.cancel(new Q),t}),c=t.toFixed(2),u=new Z(e.verifyCard({addFrame:(e,t)=>{o&&o(e,t,l)},amount:Number(c),bin:r,challengeRequested:s,nonce:n,removeFrame:a,onLookupComplete:(e,t)=>{t()},collectDeviceData:!0,additionalInformation:d}));return u.promise}}class ce{constructor(e){this.paymentIntegrationService=e,this.braintreeHostWindow=window}render(e,t,i){const n=t&&document.getElementById(t);if(this.braintreeHostWindow.paypal&&n){const r=this.paymentIntegrationService.getState(),o=r.getCartOrThrow(),a=r.getBillingAddressOrThrow(),s=r.getPaymentMethodOrThrow(e);if(!s.initializationData)return;const{paypalBNPLConfiguration:d=[]}=s.initializationData,l=i===se.PAYMENT?"checkout":i,c=d&&d.find(({id:e})=>e===l);if(!c||!c.status)return;i===se.CART&&(n.removeAttribute("data-pp-style-logo-type"),n.removeAttribute("data-pp-style-logo-position"),n.removeAttribute("data-pp-style-text-color"),n.removeAttribute("data-pp-style-text-size")),this.braintreeHostWindow.paypal.Messages({amount:o.cartAmount,buyerCountry:a.countryCode,placement:i,style:this.getPaypalMessagesStylesFromBNPLConfig(c)}).render(`#${t}`)}}getPaypalMessagesStylesFromBNPLConfig({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t}}class ue{constructor(e){const{element:t,closeElement:i,mainElement:n}=this._createElements(e);this._element=t,this._closeElement=i,this._mainElement=n}show(e){this._mainElement.parentElement||(this._registerClick(e),document.body.appendChild(this._mainElement),setTimeout(()=>this._element.style.opacity="1"))}remove(){this._mainElement.parentElement&&(this._unregisterClick&&this._unregisterClick(),this._removeAfterTransition(),setTimeout(()=>this._element.style.opacity="0"))}_createElements(e){const t=document.createElement("div"),{background:i="rgba(0, 0, 0, 0.8)",id:n="checkoutOverlay",transitionDuration:r=400,hasCloseButton:o=!1,innerHtml:a=null}=e||{};let s,d,l,c,u=t;if(n&&(t.id=n),a){const e=document.createElement("div");c=`${n}--overlayText`,e.className=c,e.appendChild(a),t.appendChild(e)}return o&&(l=`${n}--close`,s=document.createElement("div"),s.className=l,d=`${n}--layout`,u=document.createElement("div"),u.className=d,u.appendChild(t),u.appendChild(s)),u.appendChild(function(e){const{id:t,background:i,transitionDuration:n,classLayout:r,classOverlayText:o,classClose:a}=e,s=document.createElement("style"),d=r?`, .${r}`:"";return s.id=`${t}--styles`,s.type="text/css",s.innerText=`\n #${t}${d} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${t} {\n transition: opacity ${n}ms ease-out;\n background: ${i};\n opacity: 0;\n }\n `,o&&(s.innerText+=`\n #${t} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${t} .${o} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `),a&&(s.innerText+=`\n #${t} {\n opacity: 1;\n }\n .${r} .${a} {\n position: fixed;\n right: 16px;\n top: 16px;\n width: 16px;\n height: 16px;\n opacity: 0.6;\n cursor: pointer;\n z-index: 3147483647;\n }\n .${r} .${a}::after, .${r} .${a}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${r} .${a}::after {\n transform: rotate(-45deg);\n }\n .${r} .${a}::before {\n transform: rotate(45deg);\n }\n `),s}({id:n,background:i,transitionDuration:r,classLayout:d,classOverlayText:c,classClose:l})),{element:t,closeElement:s,mainElement:u}}_addEventListener(e,t){e&&t&&e.addEventListener("click",t)}_removeEventListener(e,t){e&&t&&e.removeEventListener("click",t)}_registerClick(e){if(this._unregisterClick&&this._unregisterClick(),e){const{onClick:t,onClickClose:i}=e;this._addEventListener(this._element,t),this._addEventListener(this._closeElement,i),this._unregisterClick=()=>{this._removeEventListener(this._element,t),this._removeEventListener(this._closeElement,i),this._unregisterClick=void 0}}}_removeAfterTransition(){const e=t=>{"opacity"===t.propertyName&&(this._mainElement.parentElement&&this._mainElement.remove(),this._element.removeEventListener("transitionend",e))};this._element.addEventListener("transitionend",e)}}const he={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},ye="embedded-checkout-loading-indicator-rotation";class me{constructor(e){this.styles=Object.assign(Object.assign({},he),e&&e.styles),this.containerStyles=Object.assign({},e&&e.containerStyles),this.defineAnimation(),this.container=this.buildContainer(),this.indicator=this.buildIndicator(),this.container.appendChild(this.indicator)}show(e){if(e){const t=document.getElementById(e);if(!t)throw new Error("Unable to attach the loading indicator because the parent ID is not valid.");t.appendChild(this.container)}this.container.style.visibility="visible",this.container.style.opacity="1"}hide(){const e=()=>{this.container.style.visibility="hidden",this.container.removeEventListener("transitionend",e)};this.container.addEventListener("transitionend",e),this.container.style.opacity="0"}buildContainer(){const e=document.createElement("div");return e.style.display="block",e.style.bottom="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.position="absolute",e.style.right="0",e.style.top="0",e.style.transition="all 250ms ease-out",e.style.opacity="0",this.setStyleAttribute(e,this.containerStyles),e}buildIndicator(){const e=document.createElement("div");return e.style.display="block",e.style.width=`${this.styles.size}px`,e.style.height=`${this.styles.size}px`,e.style.borderRadius=`${this.styles.size}px`,e.style.border="solid 1px",e.style.borderColor=`${this.styles.backgroundColor} ${this.styles.backgroundColor} ${this.styles.color} ${this.styles.color}`,e.style.margin="0 auto",e.style.position="absolute",e.style.left="0",e.style.right="0",e.style.top="50%",e.style.transform="translateY(-50%) rotate(0deg)",e.style.transformStyle="preserve-3d",e.style.animation=`${ye} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])})}defineAnimation(){var e;if(document.getElementById(ye))return;const t=document.createElement("style");t.id=ye,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${ye} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}const pe={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};function ge(e){return"object"==typeof e&&null!==e&&"name"in e&&"BraintreeError"===e.name}function ve(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}var fe=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class be{constructor(e,t,i,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeMessages=i,this.loadingIndicator=n,this.braintreeHostWindow=window}initialize(e){return fe(this,void 0,void 0,function*(){const{braintree:t,methodId:i}=e;if(this.braintree=t,this.paymentMethod&&this.paymentMethod.nonce||(this.paymentMethod=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i)),this.paymentMethod.clientToken&&(null==t?void 0:t.bannerContainerId))return yield this.loadPaypal(),this.loadPaypalCheckoutInstance();if(this.paymentMethod.clientToken)return this.loadPaypal();const n=yield this.paymentIntegrationService.loadPaymentMethod(i);if(this.paymentMethod=n.getPaymentMethodOrThrow(i),null==t?void 0:t.bannerContainerId)return this.loadPaypalCheckoutInstance();if(!this.paymentMethod.clientToken)throw new U(j.MissingPaymentMethod);return this.loadPaypal()})}execute(e,t){var i;return fe(this,void 0,void 0,function*(){const{payment:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{onError:o}=this.braintree||{};if(!n)throw new R(["payment"]);try{const e=yield this.preparePaymentData(n,r.useStoreCredit);yield this.paymentIntegrationService.submitOrder(r,t),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.isProviderError(e)&&(yield this.loadPaypal(),null===(i=this.paypalButtonRender)||void 0===i||i.close(),yield this.loadPaypalCheckoutInstance(),yield new Promise((e,t)=>{o&&"function"==typeof o&&o(new Error("INSTRUMENT_DECLINED")),t()})),this.handleError(e)}})}finalize(){return Promise.reject(new W)}deinitialize(){var e;return this.braintreeTokenizePayload=void 0,null===(e=this.paypalButtonRender)||void 0===e||e.close(),this.braintreeIntegrationService.teardown()}preparePaymentData(e,t){var i;return fe(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),r=n.getOutstandingBalance(t),o=n.getStoreConfig();if(!r)throw new U(j.MissingCheckout);if(!o)throw new U(j.MissingCheckoutConfig);if(!this.paymentMethod)throw new M(C.PaymentNotInitialized);const{currency:a,storeProfile:{storeLanguage:s}}=o,{nonce:d,config:{isVaultingEnabled:l}}=this.paymentMethod,{methodId:c,paymentData:u={}}=e,h=(null===(i=this.braintreeTokenizePayload)||void 0===i?void 0:i.nonce)||d;if(h){const t=yield this.paymentIntegrationService.loadPaymentMethod(c);return this.paymentMethod=t.getPaymentMethod(c),Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(h)})}if(H(u)||(y=u,Boolean(y.instrumentId)&&!Object.prototype.hasOwnProperty.call(y,"ccNumber")&&!Object.prototype.hasOwnProperty.call(y,"ccCvv"))){if(!l)throw new V("Vaulting is disabled but a vaulted instrument was being used for this transaction");return Promise.resolve(e)}var y;if(!q(u))throw new U(j.MissingPayment);const{shouldSaveInstrument:m,shouldSetAsDefaultInstrument:p}=u;if(m&&!l)throw new V("Vaulting is disabled but shouldSaveInstrument is set to true");const g=n.getShippingAddress(),v=g?ve(g):void 0;return Promise.all([this.braintreeIntegrationService.paypal({amount:r,locale:s,currency:a.code,offerCredit:"braintreepaypalcredit"===this.paymentMethod.id,shippingAddressOverride:v,shouldSaveInstrument:m||!1,shippingAddressEditable:!1}),this.braintreeIntegrationService.getSessionId()]).then(([{nonce:t,details:i}={},n])=>Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(t,i&&i.email,n,m,p)}))})}formattedPayload(e,t,i,n,r){return{formattedPayload:{vault_payment_instrument:n||null,set_as_default_stored_instrument:r||null,device_info:i||null,paypal_account:{token:e,email:t||null}}}}loadPaypalCheckoutInstance(){return fe(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t,id:i}=this.paymentMethod||{};if(!e)throw new U(j.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e);const n={currency:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,intent:null==t?void 0:t.intent,isCreditEnabled:null==t?void 0:t.isCreditEnabled},r="braintreepaypalcredit"===i||!(null==t?void 0:t.isCreditEnabled);yield this.braintreeIntegrationService.getPaypalCheckout(n,e=>{var t;r&&i&&(null===(t=this.braintree)||void 0===t?void 0:t.bannerContainerId)&&this.renderPayPalMessages(i,this.braintree.bannerContainerId),this.renderPayPalButton(e)},this.handleError)}catch(e){this.handleError(e)}})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,se.PAYMENT)}renderPayPalButton(e){const{onPaymentError:t,submitForm:i,onRenderButton:n,containerId:r,onError:o}=this.braintree||{};if(!r)return;if(!this.paymentMethod)throw new M(C.PaymentNotInitialized);this.loadingIndicatorContainer=r.split("#")[1];const{id:a,config:{testMode:s}}=this.paymentMethod,{paypal:d}=this.braintreeHostWindow,l=null==d?void 0:d.FUNDING.PAYPAL;d&&l?(this.paypalButtonRender=d.Buttons({env:s?"sandbox":"production",commit:!1,fundingSource:l,onClick:()=>{this.toggleLoadingIndicator(!0)},createOrder:()=>this.setupPayment(e,a,t),onApprove:t=>fe(this,void 0,void 0,function*(){this.braintreeTokenizePayload=yield this.tokenizePaymentOrThrow(t,e),i&&"function"==typeof i&&i()}),onCancel:()=>{this.toggleLoadingIndicator(!1)},onError:e=>{this.toggleLoadingIndicator(!1),null==o||o(e)}}),n&&"function"==typeof n&&n(),this.paypalButtonRender.isEligible()&&this.paypalButtonRender.render(`${r}`)):this.removeElement(r.split("#")[1])}setupPayment(e,t,i){return fe(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState();try{const i=n.getCustomer(),r=n.getPaymentMethodOrThrow(t),o=n.getCheckoutOrThrow().outstandingBalance,a=n.getStoreConfigOrThrow().currency.code,s=n.getShippingAddress()||(null==i?void 0:i.addresses[0]),d=s?ve(s):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:d,amount:o,currency:a,offerCredit:!1,intent:r.initializationData.intent})}catch(e){throw i&&(ge(e)||e instanceof p)&&i(e),e}})}tokenizePaymentOrThrow(e,t,i){return fe(this,void 0,void 0,function*(){try{return yield t.tokenizePayment(e)}catch(e){throw i&&(ge(e)||e instanceof p)&&i(e),e}})}loadPaypal(){return fe(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t}=this.paymentMethod||{};if(!e||!t)throw new U(j.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e),yield this.braintreeIntegrationService.getPaypal()}catch(e){this.handleError(e)}return Promise.resolve()})}handleError(e){if(!ge(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Q(e.message);throw new $(e.message)}isProviderError(e){var t,i,n;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"2046"===(null===(n=null===(i=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===i?void 0:i.provider_error)||void 0===n?void 0:n.code)}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const we=L(t=>{const i=window,n=new ue,r=new F(t),o=new le(new z(e(),i,r),i,n),a=new ce(t);return new be(t,o,a,new me({containerStyles:pe}))},[{id:"braintreepaypal"},{id:"braintreepaypalcredit"}]);var Ce;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(Ce||(Ce={}));const Se=Ce,Pe={"X-Checkout-SDK-Version":"1.857.0"};class Ie{constructor(e){this.requestSender=e}getOrderStatus(e="braintreelocalmethods",t){return i=this,n=void 0,o=function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":"This API endpoint is for internal use only and may change in the future","Content-Type":Se.Json},Pe);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}const Oe={body:{},headers:{},status:0};class ke extends p{constructor(e,{message:t,errors:i}={}){const{body:n,headers:r,status:o}=e||Oe;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=n,this.headers=r,this.status=o,this.errors=i||[]}}class Ee extends ke{constructor(e){super(e,{message:"There is a problem processing your payment. Please try again later."}),this.name="PaymentMethodInvalidError",this.type="payment_method_invalid"}}class Te extends ke{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var Ae=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ze{constructor(e,t,i,n,r=3e3,a=3e5){this.paymentIntegrationService=e,this.braintreeSdk=t,this.braintreeRequestSender=i,this.loadingIndicator=n,this.pollingInterval=r,this.maxPollingIntervalTime=a,this.isLPMsUpdateExperimentEnabled=!1,this.pollingTimer=0,this.stopPolling=o,this.isPollingEnabled=!1}initialize(e){return Ae(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,braintreelocalmethods:n}=e;if(this.gatewayId=t,!i)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new V('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new V('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');this.braintreelocalmethods=n,this.loadingIndicatorContainer=n.container.split("#")[1],yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(t),{clientToken:a,config:s,initializationData:d}=o,l=r.getStoreConfigOrThrow().checkoutSettings.features;if(this.isPollingEnabled=x(l,"PAYPAL-5258.braintree_local_methods_polling"),this.isLPMsUpdateExperimentEnabled=x(l,"PAYPAL-4853.add_new_payment_flow_for_braintree_lpms"),!a||!d||!s.merchantId)throw new U(j.MissingPaymentMethod);try{this.braintreeSdk.initialize(a),this.isNonInstantPaymentMethod(i)||(this.braintreeLocalPayment=yield this.braintreeSdk.getBraintreeLocalPayment(s.merchantId))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new W)}deinitialize(){return Ae(this,void 0,void 0,function*(){return this.toggleLoadingIndicator(!1),Promise.resolve()})}execute(e,t){return Ae(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new R(["payment"]);const{methodId:r}=i;this.toggleLoadingIndicator(!0),this.isNonInstantPaymentMethod(r)?yield this.executeWithNotInstantLPM(r):yield this.executeWithInstantLPM(r,n,t)})}executeWithNotInstantLPM(e){return Ae(this,void 0,void 0,function*(){try{const t=yield this.getLPMsBasicPaymentData();yield this.paymentIntegrationService.submitOrder(),yield this.paymentIntegrationService.submitPayment({methodId:e,paymentData:Object.assign(Object.assign({},t),{formattedPayload:{method:e}})})}catch(e){if(this.isBraintreeRedirectError(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise((e,i)=>{window.location.replace(t),this.toggleLoadingIndicator(!1),i()})}return this.handleError(e),Promise.reject(e)}})}executeWithInstantLPM(e,t,i){return Ae(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment)throw new Ee;yield new Promise((n,r)=>{var o;null===(o=this.braintreeLocalPayment)||void 0===o||o.startPayment(this.getInstantLPMConfig(e,t,i),this.getInstantLPMCallback(n,r,e,t,i))})})}getLPMsBasicPaymentData(){return Ae(this,void 0,void 0,function*(){const{deviceData:e}=yield this.braintreeSdk.getDataCollectorOrThrow();return{deviceSessionId:e}})}getInstantLPMConfig(e,t,i){const n=this.paymentIntegrationService.getState(),r=n.getCartOrThrow(),o=n.getBillingAddressOrThrow(),{firstName:a,lastName:s,countryCode:d}=o,{currency:l,email:c,lineItems:u}=r,h=u.physicalItems.length>0,y=n.getCheckoutOrThrow().outstandingBalance,m=n.getStoreConfigOrThrow().links.checkoutLink;return{paymentType:e,amount:y,fallback:{url:m,buttonText:"Complete Payment"},currencyCode:l.code,shippingAddressRequired:h,email:c,givenName:a,surname:s,address:{countryCode:d},onPaymentStart:(n,r)=>Ae(this,void 0,void 0,function*(){if(!this.isLPMsUpdateExperimentEnabled)return this.orderId=n.paymentId,void r();const o=yield this.getLPMsBasicPaymentData(),a=Object.assign(Object.assign({},o),{formattedPayload:{method:e,[`${e}_account`]:{order_id:n.paymentId}}});try{yield this.paymentIntegrationService.submitOrder(t,i),yield this.paymentIntegrationService.submitPayment({methodId:e,paymentData:a})}catch(t){if(this.isBraintreeOrderSavedResponse(t)&&t.body.additional_action_required.data.order_id_saved_successfully)return r(),this.isPollingEnabled?new Promise((t,i)=>{this.initializePollingMechanism(e,t,i,this.gatewayId)}):void 0;throw t}})}}getInstantLPMCallback(e,t,i,n,r){const o=this.paymentIntegrationService.getState().getCartOrThrow();return(a,s)=>Ae(this,void 0,void 0,function*(){if(a)return"LOCAL_PAYMENT_WINDOW_CLOSED"===a.code?(this.toggleLoadingIndicator(!1),this.resetPollingMechanism(),t()):(this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t(new Ee));const d=yield this.getLPMsBasicPaymentData(),l=Object.assign(Object.assign({},d),{formattedPayload:{method:i,[`${i}_account`]:Object.assign({email:o.email,token:s.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId})}});try{return this.isLPMsUpdateExperimentEnabled||(yield this.paymentIntegrationService.submitOrder(n,r)),yield this.paymentIntegrationService.submitPayment({methodId:i,paymentData:l}),e(void 0)}catch(e){return this.handleError(e),t(e)}})}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}handleError(e){const{onError:t}=this.braintreelocalmethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}isNonInstantPaymentMethod(e){return e.toUpperCase()in I}isBraintreeRedirectError(e){var t;if("object"!=typeof e||null===e)return!1;const{body:i}=e;return!!i&&!!(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}isBraintreeOrderSavedResponse(e){var t;if("object"!=typeof e||null===e)return!1;const{body:i}=e;return!!i&&(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.hasOwnProperty("order_id_saved_successfully"))}initializePollingMechanism(e,t,i,n){return Ae(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.braintreeRequestSender.getOrderStatus(n,{params:{useMetadata:!1}}),o=r.status===P.Pending,a=r.status===P.Completed,s=r.status===P.Failed;if(a)return this.deinitializePollingMechanism(),t();if(s)return i();if(!a&&o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,braintreelocalmethods:this.braintreelocalmethods}),this.handleError(new Te)}catch(e){i()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}reinitializeStrategy(e){return Ae(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}}const Ne=L(t=>{const i=window,n=new F(t),r=new B(new z(e(),i,n)),o=c(),a=new Ie(o);return new ze(t,r,a,new me({styles:{backgroundColor:"black"}}))},[{gateway:"braintreelocalmethods"}]);function Me(e){return"string"!=typeof e}function De(e,t){if(t||e)return function(e){var t,i;const n={},r=s(e.root,Me),o=s(e.input,Me),a=s(e.toggle,Me),d=s(null===(t=e.text)||void 0===t?void 0:t.body,Me),l=s(null===(i=e.text)||void 0===i?void 0:i.caption,Me),c=e.branding;return Object.keys(r).length&&(n.root=r),Object.keys(o).length&&(n.input=o),Object.keys(a).length&&(n.toggle=a),Object.keys(d).length&&(n.text={},n.text.body=d),Object.keys(l).length&&(n.text=Object.assign({},n.text),n.text.caption=l),c&&(n.branding=c),n}(function(e,t){var i,n,r,o,a,s,d,l,c,u,h,y,m,p,g,v,f,b,w,C,S,P;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(y=null==t?void 0:t.input)||void 0===y?void 0:y.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(p=null==t?void 0:t.toggle)||void 0===p?void 0:p.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(b=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===b?void 0:b.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(C=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===C?void 0:C.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(P=null===(S=null==t?void 0:t.text)||void 0===S?void 0:S.caption)||void 0===P?void 0:P.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}function _e(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var Be,xe=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Fe{constructor(e,t,i){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.braintreeSdk=i}initialize(e){var t;return xe(this,void 0,void 0,function*(){const{methodId:i,braintreefastlane:n}=e;if(!i)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new V('Unable to initialize payment because "options.braintreefastlane" argument is not provided.');if(!n.onInit||"function"!=typeof n.onInit)throw new V('Unable to initialize payment because "options.braintreefastlane.onInit" argument is not provided or it is not a function.');if(!n.onChange||"function"!=typeof n.onChange)throw new V('Unable to initialize payment because "options.braintreefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(i),{initializationData:a,clientToken:s}=o||{},{isFastlaneStylingEnabled:d}=a||{},l=x(r.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");this.is3DSEnabled=o.config.is3dsEnabled,s&&l&&this.braintreeSdk.initialize(s);const c=De(d?null===(t=o.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,n.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(i,c),this.shouldRunAuthenticationFlow()&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow()),yield this.initializeCardComponent(),this.onError=n.onError,n.onInit(e=>this.renderBraintreeCardComponent(e)),n.onChange(()=>this.handleBraintreeStoredInstrumentChange(i))})}execute(e,t){return xe(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new R(["payment"]);yield this.paymentIntegrationService.submitOrder(n,t);const r=yield this.preparePaymentPayload(i.methodId);yield this.paymentIntegrationService.submitPayment(r),this.braintreeFastlaneUtils.removeSessionIdFromCookies()})}finalize(){return Promise.reject(new W)}deinitialize(){return xe(this,void 0,void 0,function*(){return this.braintreeCardComponent=void 0,Promise.resolve()})}initializeCardComponent(){return xe(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),{phone:t,firstName:i,lastName:n}=e.getBillingAddressOrThrow(),r=`${i} ${n}`,o={styles:{},fields:Object.assign({cardholderName:{prefill:r,enabled:!0}},t&&{phoneNumber:{prefill:t}})},a=this.braintreeFastlaneUtils.getBraintreeFastlaneComponentOrThrow();this.braintreeCardComponent=yield a(o)})}renderBraintreeCardComponent(e){const t=this.getBraintreeCardComponentOrThrow();if(!e)throw new V('Unable to initialize payment because "container" argument is not provided.');t.render(e)}preparePaymentPayload(e){var t,i;return xe(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),r=n.getBillingAddressOrThrow(),o=`${r.firstName} ${r.lastName}`,a=this.getPayPalInstruments()[0],s=yield this.braintreeFastlaneUtils.getDeviceSessionId(),d=x(n.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");if(a){const t=this.is3DSEnabled&&d?yield this.get3DS(a.bigpayToken,(null==a?void 0:a.iin)||""):void 0;return{methodId:e,paymentData:{deviceSessionId:s,formattedPayload:{paypal_fastlane_token:{token:t||a.bigpayToken}}}}}const{getPaymentToken:l}=this.getBraintreeCardComponentOrThrow(),c=yield l({name:{fullName:o},billingAddress:this.mapToPayPalAddress(r)}),u=(null===(i=null===(t=c.paymentSource.card)||void 0===t?void 0:t.binDetails)||void 0===i?void 0:i.bin)||"",h=this.is3DSEnabled&&d?yield this.get3DS(c.id,u):void 0;return{methodId:e,paymentData:{deviceSessionId:s,nonce:h||c.id}}})}get3DS(e,t){return xe(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=yield this.braintreeSdk.getBraintreeThreeDS(),r=i.getOrderOrThrow();return new Promise((i,o)=>{n.verifyCard({amount:null==r?void 0:r.orderAmount,nonce:e,bin:t,onLookupComplete:(e,t)=>{n.on("customer-canceled",()=>{"function"==typeof this.onError&&this.onError(new Q),o(new Q)}),t()}},(e,t)=>(e&&"THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT"===e.code&&("function"==typeof this.onError&&this.onError(new Q),o(new Q)),i(t.nonce)))})})}mapToPayPalAddress(e){return{streetAddress:(null==e?void 0:e.address1)||"",locality:(null==e?void 0:e.city)||"",region:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCodeAlpha2:(null==e?void 0:e.countryCode)||""}}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getCustomerOrThrow(),n=e.getPaymentProviderCustomer(),r=_e(n)?n:{},o=this.braintreeFastlaneUtils.getSessionIdFromCookies();return!(!i.isGuest||(null==r?void 0:r.authenticationState)===O.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}getBraintreeCardComponentOrThrow(){if(!this.braintreeCardComponent)throw new g;return this.braintreeCardComponent}getPayPalInstruments(){const e=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow();return(_e(e)?e:{}).instruments||[]}handleBraintreeStoredInstrumentChange(e){return xe(this,void 0,void 0,function*(){const t=this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow(),{selectionChanged:i,selectedCard:n}=yield t.profile.showCardSelector();if(i){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),i=_e(t)?t:{},r=this.braintreeFastlaneUtils.mapPayPalToBcInstrument(e,[n]);if(r&&r.length>0)return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},i),{instruments:[...r]})),r[0]}})}}!function(e){e.CVV="cvv",e.PAN="pan"}(Be||(Be={}));class Le{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,i=document.cookie;let n=null;const r=i.indexOf(t);if(r>-1){let e=i.indexOf(";",r);-1===e&&(e=i.length),n=decodeURIComponent(i.substring(r+t.length,e))}return n}static set(e,t,i={secure:!0}){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:r,path:o,domain:a,secure:s}=i;if(r)n+=`; expires=${r.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),n+=`; expires=${e.toUTCString()}`}o&&(n+=`; path=${o}`),a&&(n+=`; domain=${a}`),s&&(n+="; secure"),document.cookie=n}static remove(e,t){Le.set(e,"",Object.assign({expires:new Date(0)},t))}}var Ve=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class je{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}getDeviceSessionId(){return Ve(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getCart();return this.braintreeIntegrationService.getSessionId(null==e?void 0:e.id)})}initializeBraintreeFastlaneOrThrow(e,t){return Ve(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getCart(),{clientToken:r,config:o}=i.getPaymentMethodOrThrow(e);if(!r)throw new U(j.MissingPaymentMethod);this.methodId=e,this.braintreeIntegrationService.initialize(r),this.braintreeFastlane=yield this.braintreeIntegrationService.getBraintreeFastlane(null==n?void 0:n.id,o.testMode,t)})}getBraintreeFastlaneOrThrow(){if(!this.braintreeFastlane)throw new g;return this.braintreeFastlane}getBraintreeFastlaneComponentOrThrow(){return this.getBraintreeFastlaneOrThrow().FastlaneCardComponent}runPayPalAuthenticationFlowOrThrow(e,t){var i;return Ve(this,void 0,void 0,function*(){try{const n=this.getMethodIdOrThrow(),r=this.getBraintreeFastlaneOrThrow(),{lookupCustomerByEmail:o,triggerAuthenticationFlow:a}=r.identity,s=this.paymentIntegrationService.getState(),d=s.getCartOrThrow(),l=s.getCustomer(),c=s.getBillingAddress(),{isFastlaneShippingOptionAutoSelectEnabled:u}=s.getPaymentMethodOrThrow(n).initializationData||{},h=e||(null==l?void 0:l.email)||(null==c?void 0:c.email)||"",{customerContextId:y}=yield o(h);if(!y)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:O.UNRECOGNIZED,addresses:[],instruments:[]}),void this.saveSessionIdToCookies(d.id);const{authenticationState:m,profileData:p}=yield a(y),g=(null===(i=null==p?void 0:p.shippingAddress)||void 0===i?void 0:i.phoneNumber)||"";if(m===O.CANCELED)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:[],instruments:[]}),void this.removeSessionIdFromCookies();const v=this.mapPayPalToBcAddress([p.shippingAddress],[g])||[],f=this.getPayPalBillingAddresses(p),b=f?this.mapPayPalToBcAddress([f],[g]):[],w=p.card?this.mapPayPalToBcInstrument(n,[p.card]):[],C=this.mergeShippingAndBillingAddresses(v,b);if(this.saveSessionIdToCookies(d.id),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:C,instruments:w}),b.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateBillingAddress(b[0])),b.length>0&&d.lineItems.digitalItems.length>0&&0===d.lineItems.physicalItems.length){const{firstName:e,lastName:t}=C[0],i=Object.assign(Object.assign({},b[0]),{firstName:e,lastName:t});yield this.paymentIntegrationService.updateBillingAddress(i)}v.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateShippingAddress(v[0]),t&&u&&(yield this.setShippingOption()))}catch(e){}})}getSessionIdFromCookies(){return Le.get("bc-fastlane-sessionId")||""}saveSessionIdToCookies(e){const t=new Date;t.setDate(t.getDate()+14),Le.set("bc-fastlane-sessionId",e,{expires:t,secure:!0})}removeSessionIdFromCookies(){Le.remove("bc-fastlane-sessionId")}mapPayPalToBcInstrument(e,t){if(t)return t.map(t=>{const{id:i,paymentSource:n}=t,{brand:r,expiry:o,lastDigits:a,binDetails:s}=n.card,[d,l]=o.split("-");return{bigpayToken:i,brand:r,defaultInstrument:!1,expiryMonth:l,expiryYear:d,iin:(null==s?void 0:s.bin)||"",last4:a,method:e,provider:e,trustedShippingAddress:!1,type:"card",untrustedShippingCardVerificationMode:Be.PAN}})}mapPayPalToBcAddress(e,t){if(!e)return[];const i=this.paymentIntegrationService.getState().getCountries()||[],n=e=>{const t=i.find(t=>t.code===e);return(null==t?void 0:t.name)||""};return e.map(e=>({id:Date.now(),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:n(e.countryCodeAlpha2),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:t&&t[0]||"",customFields:[]}))}getPayPalBillingAddresses(e){const{card:t,name:i}=e||{};if(!t)return;const{firstName:r,lastName:o}=t.paymentSource.card.billingAddress,{firstName:a,lastName:s}=i||{},{shippingAddress:d}=e||{},l=Object.assign(Object.assign({},t.paymentSource.card.billingAddress),{firstName:r||a,lastName:o||s});return d&&n(this.normalizeAddress(l),this.normalizeAddress(d))?d:l}normalizeAddress(e){return a(e,["id"])}mergeShippingAndBillingAddresses(e,t){const i=t.filter(t=>!e.some(e=>n(this.normalizeAddress(e),this.normalizeAddress(t))));return[...e,...i]}getMethodIdOrThrow(){if(!this.methodId)throw new V('Unable to proceed because "methodId" argument is not provided.');return this.methodId}setShippingOption(){var e;return Ve(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getConsignments()||[],i=(null===(e=t[0])||void 0===e?void 0:e.availableShippingOptions)||[],n=i.find(e=>e.isRecommended);if(n||i.length){const e=n||i[0];yield this.paymentIntegrationService.selectShippingOption(e.id)}})}}const Ue=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i),o=new je(t,r),a=new z(e(),i,n),s=new B(a);return new Fe(t,o,s)},[{id:"braintreeacceleratedcheckout"}]);var Re=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class He{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i}initialize(e){return Re(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:i}=e;if(!t)throw new V('Unable to initialize payment because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState();this.paymentMethod=n.getPaymentMethodOrThrow(i);const r=n.getCheckoutOrThrow(),a=n.getStoreConfigOrThrow(),{clientToken:s,config:d}=this.paymentMethod||{};if(!s)throw new U(j.MissingPaymentMethod);const{onError:l=o,onPaymentSelect:c=o}=t;this.braintreeSdk.initialize(s);const u=yield this.braintreeSdk.getBraintreeVisaCheckout(),h=yield this.braintreeSdk.getVisaCheckoutSdk(null==d?void 0:d.testMode),y=u.createInitOptions({settings:{locale:a.storeProfile.storeLanguage,shipping:{collectShipping:!1}},paymentRequest:{currencyCode:a.currency.code,subtotal:String(r.subtotal)}});yield h.init(y),h.on("payment.success",e=>this.tokenizePayment(u,e).then(()=>Promise.all([this.paymentIntegrationService.loadCheckout(),this.paymentIntegrationService.loadPaymentMethod(i)])).then(()=>c()).catch(e=>l(e))),h.on("payment.error",(e,t)=>l(t))})}execute(e,t){var i,n;return Re(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!r)throw new V('Unable to submit payment because "payload.payment" argument is not provided.');if(!(null===(n=null===(i=this.paymentMethod)||void 0===i?void 0:i.initializationData)||void 0===n?void 0:n.nonce))throw new U(j.MissingPaymentMethod);const{nonce:a}=this.paymentMethod.initializationData;try{yield this.paymentIntegrationService.submitOrder(o,t),yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},r),{paymentData:{nonce:a}}))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new W)}deinitialize(){return Re(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}tokenizePayment(e,t){return Re(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(n),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}handleError(e){if(e instanceof Error&&"BraintreeError"===e.name)throw new $(e.message);throw e}}const We=L(t=>{const i=window,n=new F(t),r=new B(new z(e(),i,n));return new He(t,u(),r)},[{id:"braintreevisacheckout"}]);var qe=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class $e{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}initialize(e){return qe(this,void 0,void 0,function*(){const{methodId:t}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState();this.venmoOptions=e.braintreevenmo;const n=i.getPaymentMethodOrThrow(t);yield this.initializeBraintreeVenmo(n)})}execute(e){return qe(this,void 0,void 0,function*(){const{payment:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!t)throw new R(["payment"]);try{const e=yield this.preparePaymentData(t);yield this.paymentIntegrationService.submitOrder(i),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new W)}deinitialize(){return qe(this,void 0,void 0,function*(){return yield this.braintreeIntegrationService.teardown(),Promise.resolve()})}handleError(e){if(!D(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Q(e.message);throw new $(e.message)}initializeBraintreeVenmo(e){var t;return qe(this,void 0,void 0,function*(){const{clientToken:i}=e;if(!i)throw new U(j.MissingPaymentMethod);const n=x(this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features,"PAYPAL-5406.braintree_venmo_web_fallback_support");try{this.braintreeIntegrationService.initialize(i),this.braintreeVenmoCheckout=yield this.braintreeIntegrationService.getVenmoCheckout(Object.assign(Object.assign({},void 0!==(null===(t=this.venmoOptions)||void 0===t?void 0:t.allowDesktop)?{allowDesktop:this.venmoOptions.allowDesktop}:{}),n?{mobileWebFallBack:n}:{}))}catch(e){this.handleError(e)}})}preparePaymentData(e){return qe(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{nonce:i}=t.getPaymentMethodOrThrow(e.methodId);if(i)return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(i)});const n=yield this.braintreeVenmoTokenize(),r=yield this.braintreeIntegrationService.getSessionId();return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(n.nonce,n.details.email,r)})})}formattedPayload(e,t,i){return{formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:i||null,paypal_account:{token:e,email:t||null}}}}braintreeVenmoTokenize(){return new Promise((e,t)=>{var i;null===(i=this.braintreeVenmoCheckout)||void 0===i||i.tokenize((i,n)=>{if(i)return t(i);e(n)})})}}const Ge=L(t=>{const i=window,n=e(),r=new F(t),o=new z(n,i,r),a=new le(o,i);return new $e(t,a)},[{id:"braintreevenmo"}]);var Ye=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Je{constructor(e,t,i){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeHostedForm=i}initialize(e){return Ye(this,void 0,void 0,function*(){const{methodId:t,gatewayId:i,braintree:n}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState();this.paymentMethod=r.getPaymentMethodOrThrow(t);const{clientToken:o}=this.paymentMethod;if(!o)throw new U(j.MissingPaymentMethod);this.threeDSecure=null==n?void 0:n.threeDSecure,this.onPaymentError=null==n?void 0:n.onPaymentError;try{this.braintreeIntegrationService.initialize(o,this.threeDSecure),this.isHostedPaymentFormEnabled(t,i)&&(null==n?void 0:n.form)&&(yield this.braintreeHostedForm.initialize(n.form,n.unsupportedCardBrands,o),this.isHostedFormInitialized=this.braintreeHostedForm.isInitialized()),this.is3dsEnabled=this.paymentMethod.config.is3dsEnabled,this.deviceSessionId=yield this.braintreeIntegrationService.getSessionId(),this.shouldInitializeBraintreeFastlane()&&(yield this.initializeBraintreeFastlaneOrThrow(t))}catch(e){return this.handleError(e,t)}})}execute(e){return Ye(this,void 0,void 0,function*(){const{payment:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!t)throw new R(["payment"]);this.isHostedFormInitialized&&this.braintreeHostedForm.validate(),yield this.paymentIntegrationService.submitOrder(i);const n=this.paymentIntegrationService.getState(),r=n.getBillingAddressOrThrow(),o=n.getOrderOrThrow().orderAmount;try{const e=this.isHostedFormInitialized?yield this.prepareHostedPaymentData(t,r,o):yield this.preparePaymentData(t,r,o);yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},t),{paymentData:e}))}catch(e){return this.processAdditionalAction(e,t,o)}})}finalize(){return Promise.reject(new W)}deinitialize(){return Ye(this,void 0,void 0,function*(){return this.isHostedFormInitialized=!1,yield Promise.all([this.braintreeIntegrationService.teardown(),this.braintreeHostedForm.deinitialize()]),Promise.resolve()})}handleError(e,t){var i;if(ge(e)){if(!(t&&this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:t})||"HOSTED_FIELDS_INVALID_FIELD_SELECTOR"!==e.code))return;if(e.code.startsWith("THREEDS_"))return null===(i=this.onPaymentError)||void 0===i||i.call(this,new $("THREEDS_VERIFICATION_FAILED")),Promise.reject();throw new $(e.message)}throw e}preparePaymentData(e,t,i){return Ye(this,void 0,void 0,function*(){const{paymentData:n}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e))return Object.assign(Object.assign({},r),n);const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=q(n)?n:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.braintreeIntegrationService.verifyCard(e,t,i):yield this.braintreeIntegrationService.tokenizeCard(e,t);return Object.assign(Object.assign({},r),{nonce:s,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})})}prepareHostedPaymentData(e,t,i){return Ye(this,void 0,void 0,function*(){const{paymentData:n}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e)){const{nonce:e}=yield this.braintreeHostedForm.tokenizeForStoredCardVerification();return Object.assign(Object.assign(Object.assign({},r),n),{nonce:e})}const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=q(n)?n:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.verifyCardWithHostedForm(t,i):yield this.braintreeHostedForm.tokenize(t);return Object.assign(Object.assign({},r),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,nonce:s})})}verifyCardWithHostedForm(e,t){return Ye(this,void 0,void 0,function*(){const i=yield this.braintreeHostedForm.tokenize(e);return this.braintreeIntegrationService.challenge3DSVerification(i,t)})}processAdditionalAction(e,t,i){return Ye(this,void 0,void 0,function*(){if(!(e=>"object"==typeof e&&null!==e&&"body"in e)(e)||!d(e.body.errors,{code:"three_d_secure_required"}))return this.handleError(e);try{const{payer_auth_request:n}=function(e){return"object"==typeof e&&null!==e&&"name"in e&&"body"in e&&"status"in e.body&&"three_ds_result"in e.body&&"payer_auth_request"in e.body.three_ds_result&&"errors"in e.body}(e)&&e.body.three_ds_result||{},{paymentData:r}=t,o=this.paymentIntegrationService.getState();if(!r||!H(r))throw new R(["instrumentId"]);const a=o.getCardInstrumentOrThrow(r.instrumentId),{nonce:s}=yield this.braintreeIntegrationService.challenge3DSVerification({nonce:n||"",bin:a.iin},i);yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},t),{paymentData:{deviceSessionId:this.deviceSessionId,nonce:s}}))}catch(e){return this.handleError(e)}})}isHostedPaymentFormEnabled(e,t){return!!e&&!0===this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled}isSubmittingWithStoredCard(e){return!(!e.paymentData||!H(e.paymentData))}shouldPerform3DSVerification(e){return!(!this.is3dsEnabled||this.isSubmittingWithStoredCard(e))}shouldInitializeBraintreeFastlane(){var e;const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),i=_e(t)?t:{};return(null===(e=this.paymentMethod)||void 0===e?void 0:e.initializationData.isAcceleratedCheckoutEnabled)&&!(null==i?void 0:i.authenticationState)}initializeBraintreeFastlaneOrThrow(e){return Ye(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getPaymentMethodOrThrow(e),{clientToken:r,config:o}=n;if(!r)throw new U(j.MissingPaymentMethod);this.braintreeIntegrationService.initialize(r,this.threeDSecure),yield this.braintreeIntegrationService.getBraintreeFastlane(i.id,o.testMode)})}}function Ke(e){return"cardNumber"in e}function Xe(e){if(!D(e))return!1;const{details:t}=e;return void 0===t||"object"==typeof t&&null!==t&&void 0===t.invalidFieldKeys||(i=t,Array.isArray(i)&&i.every(e=>"string"==typeof e));var i}var Qe,Ze=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e[e.CreditCard=0]="CreditCard",e[e.StoredCardVerification=1]="StoredCardVerification"}(Qe||(Qe={}));class et{constructor(e,t){this.braintreeScriptLoader=e,this.braintreeSDKVersionManager=t,this.isInitializedHostedForm=!1,this.handleBlur=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onBlur)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy),errors:this.mapErrors(e.fields)})},this.handleFocus=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onFocus)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleCardTypeChange=e=>{var t,i;const n=1===e.cards.length?e.cards[0].type.replace(/^master-card$/,"mastercard"):void 0;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onCardTypeChange)||void 0===i||i.call(t,{cardType:n})},this.handleInputSubmitRequest=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onEnter)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleValidityChange=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===i||i.call(t,{isValid:this.isValidForm(e),errors:this.mapValidationErrors(e.fields)})}}initialize(e,t,n){var r,o,a,s,d;return Ze(this,void 0,void 0,function*(){this.clientToken=n,this.formOptions=e,this.type=Ke(e.fields)?Qe.CreditCard:Qe.StoredCardVerification;const l=this.mapFieldOptions(e.fields,t);i(l)?this.isInitializedHostedForm=!1:(this.cardFields=yield this.createHostedFields({fields:l,styles:e.styles&&this.mapStyleOptions(e.styles)}),null===(r=this.cardFields)||void 0===r||r.on("blur",this.handleBlur),null===(o=this.cardFields)||void 0===o||o.on("focus",this.handleFocus),null===(a=this.cardFields)||void 0===a||a.on("cardTypeChange",this.handleCardTypeChange),null===(s=this.cardFields)||void 0===s||s.on("validityChange",this.handleValidityChange),null===(d=this.cardFields)||void 0===d||d.on("inputSubmitRequest",this.handleInputSubmitRequest),this.isInitializedHostedForm=!0)})}isInitialized(){return!!this.isInitializedHostedForm}deinitialize(){var e;return Ze(this,void 0,void 0,function*(){this.isInitializedHostedForm&&(this.isInitializedHostedForm=!1,yield null===(e=this.cardFields)||void 0===e?void 0:e.teardown())})}validate(){if(!this.cardFields)throw new M(C.PaymentNotInitialized);const e=this.cardFields.getState();if(!this.isValidForm(e)){this.handleValidityChange(e);const t=this.mapValidationErrors(e.fields);throw new X(t)}}tokenize(e){var t,i,n,o,a;return Ze(this,void 0,void 0,function*(){if(!this.cardFields)throw new M(C.PaymentNotInitialized);try{const o=yield this.cardFields.tokenize(s({billingAddress:e&&this.mapBillingAddress(e)},r));return null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===i||i.call(t,{isValid:!0,errors:{}}),{nonce:o.nonce,bin:null===(n=o.details)||void 0===n?void 0:n.bin}}catch(e){if(Xe(e)){const t=this.mapTokenizeError(e);if(t)throw null===(a=null===(o=this.formOptions)||void 0===o?void 0:o.onValidate)||void 0===a||a.call(o,{isValid:!1,errors:t}),new X(t)}throw e}})}tokenizeForStoredCardVerification(){var e,t,i,n,r;return Ze(this,void 0,void 0,function*(){if(!this.cardFields)throw new M(C.PaymentNotInitialized);try{const n=yield this.cardFields.tokenize();return null===(t=null===(e=this.formOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,{isValid:!0,errors:{}}),{nonce:n.nonce,bin:null===(i=n.details)||void 0===i?void 0:i.bin}}catch(e){if(Xe(e)){const t=this.mapTokenizeError(e,!0);if(t)throw null===(r=null===(n=this.formOptions)||void 0===n?void 0:n.onValidate)||void 0===r||r.call(n,{isValid:!1,errors:t}),new X(t)}throw e}})}createHostedFields(e){return Ze(this,void 0,void 0,function*(){const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadHostedFields(),n=this.braintreeSDKVersionManager.getSDKVersion()===v?Object.assign(Object.assign({},e),{preventCursorJumps:!0}):e;return i.create(Object.assign(Object.assign({},n),{client:t}))})}getClient(){return Ze(this,void 0,void 0,function*(){if(!this.clientToken)throw new M(C.PaymentNotInitialized);if(!this.client){const e=yield this.braintreeScriptLoader.loadClient();this.client=e.create({authorization:this.clientToken})}return this.client})}mapBillingAddress(e){return{countryName:e.country,postalCode:e.postalCode,streetAddress:e.address2?`${e.address1} ${e.address2}`:e.address1}}mapFieldOptions(e,t){if(Ke(e)){const i={};return null==t||t.forEach(e=>{(e=>Object.values(T).includes(e))(e)&&(i[e]=!1)}),s({number:Object.assign({container:`#${e.cardNumber.containerId}`,placeholder:e.cardNumber.placeholder,internalLabel:e.cardNumber.accessibilityLabel},Object.keys(i).length>0?{supportedCardBrands:i}:{}),expirationDate:{container:`#${e.cardExpiry.containerId}`,placeholder:e.cardExpiry.placeholder,internalLabel:e.cardExpiry.accessibilityLabel},cvv:e.cardCode&&{container:`#${e.cardCode.containerId}`,placeholder:e.cardCode.placeholder,internalLabel:e.cardCode.accessibilityLabel},cardholderName:{container:`#${e.cardName.containerId}`,placeholder:e.cardName.placeholder,internalLabel:e.cardName.accessibilityLabel}},r)}return s({number:e.cardNumberVerification&&{container:`#${e.cardNumberVerification.containerId}`,placeholder:e.cardNumberVerification.placeholder},cvv:e.cardCodeVerification&&{container:`#${e.cardCodeVerification.containerId}`,placeholder:e.cardCodeVerification.placeholder}},r)}mapStyleOptions(e){const t=(e={})=>s({color:e.color,"font-family":e.fontFamily,"font-size":e.fontSize,"font-weight":e.fontWeight},r);return{input:t(e.default),".invalid":t(e.error),":focus":t(e.focus)}}mapFieldType(e){switch(e){case"number":return this.type===Qe.StoredCardVerification?m.CardNumberVerification:m.CardNumber;case"expirationDate":return m.CardExpiry;case"cvv":return this.type===Qe.StoredCardVerification?m.CardCodeVerification:m.CardCode;case"cardholderName":return m.CardName;default:throw new Error("Unexpected field type")}}mapErrors(e){const t={};if(e)for(const[i,n]of Object.entries(e))if(n&&this.isValidParam(i)){const{isValid:e,isEmpty:r,isPotentiallyValid:o}=n;t[i]={isValid:e,isEmpty:r,isPotentiallyValid:o}}return t}mapValidationErrors(e){return Object.keys(e).reduce((t,i)=>{var n;return Object.assign(Object.assign({},t),{[this.mapFieldType(i)]:(null===(n=e[i])||void 0===n?void 0:n.isValid)?void 0:[this.createInvalidError(this.mapFieldType(i))]})},{})}mapTokenizeError(e,t=!1){var i,n;if("HOSTED_FIELDS_FIELDS_EMPTY"===e.code){const e=[this.createRequiredError(this.mapFieldType("cvv"))];return t?{[this.mapFieldType("cvv")]:e}:{[this.mapFieldType("cvv")]:e,[this.mapFieldType("expirationDate")]:[this.createRequiredError(this.mapFieldType("expirationDate"))],[this.mapFieldType("number")]:[this.createRequiredError(this.mapFieldType("number"))],[this.mapFieldType("cardholderName")]:[this.createRequiredError(this.mapFieldType("cardholderName"))]}}return null===(n=null===(i=e.details)||void 0===i?void 0:i.invalidFieldKeys)||void 0===n?void 0:n.reduce((e,t)=>{const i=this.mapFieldType(t);return Object.assign(Object.assign({},e),{[i]:[this.createInvalidError(i)]})},{})}createRequiredError(e){var t;return{fieldType:e,message:null!==(t={[m.CardCode]:"CVV is required",[m.CardCodeVerification]:"CVV is required",[m.CardNumber]:"Credit card number is required",[m.CardNumberVerification]:"Credit card number is required",[m.CardExpiry]:"Expiration date is required",[m.CardName]:"Full name is required"}[e])&&void 0!==t?t:"Field is required",type:"required"}}createInvalidError(e){var t,i,n,r;const o={[m.CardCode]:{message:"Invalid card code",type:"invalid_card_code"},[m.CardCodeVerification]:{message:"Invalid card code",type:"invalid_card_code"},[m.CardNumber]:{message:"Invalid card number",type:"invalid_card_number"},[m.CardNumberVerification]:{message:"Invalid card number",type:"invalid_card_number"},[m.CardExpiry]:{message:"Invalid card expiry",type:"invalid_card_expiry"},[m.CardName]:{message:"Invalid card name",type:"invalid_card_name"}};return{fieldType:e,message:null!==(i=null===(t=o[e])||void 0===t?void 0:t.message)&&void 0!==i?i:"Invalid field",type:null!==(r=null===(n=o[e])||void 0===n?void 0:n.type)&&void 0!==r?r:"invalid"}}isValidForm(e){return Object.keys(e.fields).every(t=>{var i;return null===(i=e.fields[t])||void 0===i?void 0:i.isValid})}isValidParam(e){return["number","cvv","expirationDate","postalCode","cardholderName","cardType"].includes(e)}}const tt=L(t=>{const i=window,n=new F(t),r=new z(e(),i,n),o=new le(r,i),a=new et(r,n);return new Je(t,o,a)},[{id:"braintree"}]);var it=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class nt{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return it(this,void 0,void 0,function*(){const{braintreepaypal:t,methodId:i}=e,{container:n,onError:r}=t||{};if(!i)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new V('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!n)throw new V('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(i),!o.clientToken)throw new U(j.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(i),o=a.getPaymentMethodOrThrow(i)}const{clientToken:s,config:d,initializationData:l}=o,{paymentButtonStyles:c}=l||{},{checkoutTopButtonStyles:u}=c||{};if(!s||!l)throw new U(j.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:l.intent,isCreditEnabled:l.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,i,Boolean(d.testMode),u)},e=>this.handleError(e,n,r))})}deinitialize(){return it(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return it(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return it(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,i,n,r){const{container:a,onClick:s=o}=t,{paypal:d}=this.braintreeHostWindow,l=null==d?void 0:d.FUNDING.PAYPAL;if(d&&l){const o=d.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(n),fundingSource:l,style:Object.assign(Object.assign({},r),{height:40}),createOrder:()=>this.setupPayment(e,t,i),onApprove:n=>this.tokenizePayment(n,e,i,t),onClick:s});o.isEligible()&&o.render(`#${a}`)}else this.braintreeIntegrationService.removeElement(a)}setupPayment(e,t,i){var n;return it(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(i),d=null==a?void 0:a.addresses[0],l=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:l,amount:r,currency:o,offerCredit:!1,intent:null===(n=s.initializationData)||void 0===n?void 0:n.intent})}catch(e){const{container:i,onError:n}=t;this.handleError(e,i,n)}})}tokenizePayment(e,t,i,n){return it(this,void 0,void 0,function*(){try{const{deviceData:n}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:i,action:"set_external_checkout",nonce:a,device_data:n,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:i}=n;this.handleError(e,t,i)}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!D(e))throw e;i(e)}}const rt=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i);return new nt(t,u(),r,i)},[{id:"braintreepaypal"}]);var ot=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class at{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return ot(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,methodId:i}=e,{container:n,onError:r}=t||{};if(!i)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new V('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!n)throw new V('Unable to initialize payment because "options.braintreepaypalcredit.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(i),!o.clientToken)throw new U(j.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(i),o=a.getPaymentMethodOrThrow(i)}const{clientToken:s,config:d,initializationData:l}=o,{paymentButtonStyles:c}=l||{},{checkoutTopButtonStyles:u}=c||{};if(!s||!l)throw new U(j.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:l.intent,isCreditEnabled:l.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,i,Boolean(d.testMode),Object.assign(Object.assign({},u),{height:40}))},e=>this.handleError(e,n,r))})}deinitialize(){return ot(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return ot(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return ot(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,i,n,r){const{container:a,onClick:s=o}=t,{paypal:d}=this.braintreeHostWindow;let l=!1;d&&[d.FUNDING.PAYLATER,d.FUNDING.CREDIT].forEach(o=>{if(!l){const c=d.Buttons({env:n?"sandbox":"production",fundingSource:o,style:r,createOrder:()=>this.setupPayment(e,t,i),onApprove:n=>this.tokenizePayment(n,e,i,t),onClick:s});c.isEligible()&&(c.render(`#${a}`),l=!0)}}),d&&l||this.braintreeIntegrationService.removeElement(a)}setupPayment(e,t,i){var n;return ot(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(i),d=null==a?void 0:a.addresses[0],l=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:l,amount:r,currency:o,offerCredit:!0,intent:null===(n=s.initializationData)||void 0===n?void 0:n.intent})}catch(e){const{container:i,onError:n}=t;this.handleError(e,i,n)}})}tokenizePayment(e,t,i,n){return ot(this,void 0,void 0,function*(){try{const{deviceData:n}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:i,action:"set_external_checkout",nonce:a,device_data:n,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:i}=n;this.handleError(e,t,i)}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!D(e))throw e;i(e)}}const st=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i);return new at(t,u(),r,i)},[{id:"braintreepaypalcredit"}]);var dt=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class lt{constructor(e,t){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.isAcceleratedCheckoutEnabled=!1}initialize({methodId:e,braintreefastlane:t}){var i;return dt(this,void 0,void 0,function*(){if(!e)throw new V('Unable to proceed because "methodId" argument is not provided.');const n=yield this.getValidPaymentMethodOrThrow(e),{isAcceleratedCheckoutEnabled:r,isFastlaneStylingEnabled:o}=n.initializationData||{},a=o?null===(i=n.initializationData)||void 0===i?void 0:i.fastlaneStyles:void 0;this.isAcceleratedCheckoutEnabled=!!r;try{if(this.isAcceleratedCheckoutEnabled){const e=De(a,null==t?void 0:t.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(n.id,e)}}catch(e){}return Promise.resolve()})}deinitialize(){return dt(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return dt(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return dt(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return dt(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:i}=e||{};if("function"!=typeof i)throw new V('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');const n=this.paymentIntegrationService.getState().getCustomerOrThrow();if(this.isAcceleratedCheckoutEnabled&&n.isGuest){const e=yield this.shouldRunAuthenticationFlow();t&&"function"==typeof t&&t(),e&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(void 0,!0))}i()})}shouldRunAuthenticationFlow(){var e;return dt(this,void 0,void 0,function*(){const t="braintreeacceleratedcheckout";try{yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t);return(null===(e=i.initializationData)||void 0===e?void 0:e.shouldRunAcceleratedCheckout)||!1}catch(e){return!1}})}getValidPaymentMethodOrThrow(e){return dt(this,void 0,void 0,function*(){let t=e;try{yield this.paymentIntegrationService.loadPaymentMethod(t)}catch(i){t="braintree"===e?"braintreeacceleratedcheckout":"braintree",yield this.paymentIntegrationService.loadPaymentMethod(t)}return this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)})}}const ct=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i),o=new je(t,r);return new lt(t,o)},[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);class ut extends p{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var ht=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class yt{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i,this.buttonClassName="visa-checkout-wrapper",this.onError=o}initialize(e){return ht(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:i}=e;if(!i)throw new V('Unable to proceed because "methodId" argument is not provided.');if(!t)throw new V('Unable to proceed because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState(),r=n.getCheckoutOrThrow(),{clientToken:a,config:s}=n.getPaymentMethodOrThrow(i),d=n.getStoreConfigOrThrow();if(!a)throw new U(j.MissingPaymentMethod);this.braintreeSdk.initialize(a);const l=yield this.braintreeSdk.getBraintreeVisaCheckout(),c=yield this.braintreeSdk.getVisaCheckoutSdk(s.testMode),{container:u,onError:h}=t;this.onError=h||o;const y=l.createInitOptions({paymentRequest:{currencyCode:d.currency.code,subtotal:String(r.subtotal)},settings:{locale:d.storeProfile.storeLanguage,shipping:{collectShipping:!0}}}),m=this.createSignInButton(u,this.buttonClassName);yield c.init(y),c.on("payment.success",e=>this.tokenizePayment(l,e).then(()=>this.paymentIntegrationService.loadCheckout()).catch(e=>this.handleError(e))),c.on("payment.error",(e,t)=>this.handleError(t)),m.style.visibility="visible"})}deinitialize(){return ht(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}signIn(){throw new ut('In order to sign in via VisaCheckout, the shopper must click on "Visa Checkout" button.')}signOut(e){return ht(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}tokenizePayment(e,t){return ht(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(n),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e,t){const i=document.querySelector(`#${e}`);if(!i)throw new Error("Unable to proceed because the provided container ID is not valid.");return this.insertVisaCheckoutButton(i,t)}insertVisaCheckoutButton(e,t){const i=document.createElement("div");return i.style.display="flex",i.style.flexDirection="column",i.style.visibility="hidden",i.style.width="max-content",i.className=t,i.innerHTML='\n <img\n alt="Visa Checkout"\n class="v-button"\n role="button"\n src="https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178"\n />\n <a class="v-learn v-learn-default" style="text-align: right; display: block; font-size: 10px; color: #003366;" href="#" data-locale="en_US">Tell Me More</a>',e.appendChild(i),i}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const mt=L(t=>{const i=window,n=new F(t),r=new B(new z(e(),i,n));return new yt(t,u(),r)},[{id:"braintreevisacheckout"}]);class pt extends p{constructor(e){super(e||"An unexpected error has occurred during buy now cart creation process. Please try again later."),this.name="BuyNowCartCreationError",this.type="buy_now_cart_creation_error"}}function gt(e){const{color:t,fundingicons:i,height:n=40,layout:o,shape:a,size:d,tagline:l}=e||{},c={color:t,fundingicons:i,height:vt(n),layout:o,shape:a||"rect",size:d,tagline:l};return s(c,r)}function vt(e){const t=Number(e);return!t||Number.isNaN(t)?40:t>55?55:t<25?25:t}var ft=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class bt{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return ft(this,void 0,void 0,function*(){const{braintreepaypal:t,containerId:i,methodId:n}=e;if(!n)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new V('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new V('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new V('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(n),{clientToken:s,config:d,initializationData:l}=a;if(!s||!l)throw new U(j.MissingPaymentMethod);const c={currency:r,intent:l.intent,isCreditEnabled:l.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(c,e=>{this.renderPayPalButton(e,t,i,n,!!d.testMode)},e=>this.handleError(e,i,t.onError))})}deinitialize(){return ft(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,i,n,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:l}=this.braintreeHostWindow;if(l){const c=l.Buttons({env:r?"sandbox":"production",fundingSource:l.FUNDING.PAYPAL,style:gt(o),createOrder:()=>this.setupPayment(e,t,n),onApprove:t=>this.tokenizePayment(t,e,n,a,s)});c.isEligible()?c.render(`#${i}`):d&&"function"==typeof d&&d()}else this.braintreeIntegrationService.removeElement(i)}setupPayment(e,t,i){var n;return ft(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),l=s.getPaymentMethodOrThrow(i),c=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),y=h?ve(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:y,amount:c,currency:u,offerCredit:!1,intent:null===(n=l.initializationData)||void 0===n?void 0:n.intent})}catch(e){throw r&&(D(e)||e instanceof p)&&r(e),e}})}tokenizePayment(e,t,i,n,r){return ft(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),l=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:i,action:n?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(l)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(D(e)||e instanceof p)&&r(e),e}})}createBuyNowCart(e){return ft(this,void 0,void 0,function*(){if(!e)throw new U(j.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new pt}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!D(e))throw e;i(e)}}const wt=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i);return new bt(t,u(),r,i)},[{id:"braintreepaypal"}]);var Ct=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class St{constructor(e,t,i,n,r){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeMessages=n,this.braintreeHostWindow=r}initialize(e){var t,i;return Ct(this,void 0,void 0,function*(){const{braintreepaypalcredit:n,containerId:r,methodId:o}=e;if(!o)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new V('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new V('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');let a,s=this.paymentIntegrationService.getState();if(n.buyNowInitializeOptions){if(!n.currencyCode)throw new V('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');a=n.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),s=this.paymentIntegrationService.getState(),a=s.getCartOrThrow().currency.code;const d=s.getPaymentMethodOrThrow(o),{clientToken:l,config:c,initializationData:u}=d;if(!l||!u)throw new U(j.MissingPaymentMethod);const h={currency:a,intent:u.intent,isCreditEnabled:u.isCreditEnabled,commit:!1},y=x(null!==(i=null===(t=s.getStoreConfig())||void 0===t?void 0:t.checkoutSettings.features)&&void 0!==i?i:{},"PAYPAL-5663.hide_braintree_card_banner_implementation_in_checkout_sdk");this.braintreeIntegrationService.initialize(l),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{!y&&n.messagingContainerId&&this.renderPayPalMessages(o,n.messagingContainerId),this.renderPayPalButton(e,n,r,o,!!c.testMode)},e=>this.handleError(e,r,n.onError))})}deinitialize(){return Ct(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,se.CART)}renderPayPalButton(e,t,i,n,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:l}=this.braintreeHostWindow;let c=!1;l&&[l.FUNDING.PAYLATER,l.FUNDING.CREDIT].forEach(u=>{const h=u===l.FUNDING.CREDIT?Object.assign({label:oe.CREDIT},gt(o)):gt(o);if(!c){const o=l.Buttons({env:r?"sandbox":"production",fundingSource:u,style:h,createOrder:()=>this.setupPayment(e,t,n),onApprove:t=>this.tokenizePayment(t,e,n,a,s)});o.isEligible()?(o.render(`#${i}`),c=!0):l.FUNDING.CREDIT&&d&&"function"==typeof d&&d()}}),l&&c||this.braintreeIntegrationService.removeElement(i)}setupPayment(e,t,i){var n;return Ct(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),l=s.getPaymentMethodOrThrow(i),c=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),y=h?ve(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:y,amount:c,currency:u,offerCredit:!0,intent:null===(n=l.initializationData)||void 0===n?void 0:n.intent})}catch(e){throw r&&(D(e)||e instanceof p)&&r(e),e}})}tokenizePayment(e,t,i,n,r){return Ct(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),l=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:i,action:n?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(l)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(D(e)||e instanceof p)&&r(e),e}})}createBuyNowCart(e){return Ct(this,void 0,void 0,function*(){if(!e)throw new U(j.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new pt}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!D(e))throw e;i(e)}}const Pt=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i),o=new ce(t);return new St(t,u(),r,o,i)},[{id:"braintreepaypalcredit"}]);var It=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ot{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i}initialize(e){return It(this,void 0,void 0,function*(){const{containerId:t,methodId:i}=e;if(!i)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new V('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState(),{clientToken:r,initializationData:o,config:a}=n.getPaymentMethodOrThrow(i);if(!r||!o)throw new U(j.MissingPaymentMethod);this.braintreeSdk.initialize(r);const s=yield this.braintreeSdk.getBraintreeVisaCheckout(),{currency:{code:d},cartAmount:l}=n.getCartOrThrow(),c=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),u=s.createInitOptions({paymentRequest:{currencyCode:d,subtotal:String(l)},settings:{shipping:{collectShipping:!0}}});this.createSignInButton(t),yield c.init(u),c.on("payment.success",e=>It(this,void 0,void 0,function*(){yield this.paymentSuccess(s,e)}))})}deinitialize(){return Promise.resolve()}paymentSuccess(e,t){return It(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.toVisaCheckoutAddress(n),billingAddress:a=this.toVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}toVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e){const t=document.querySelector(`#${e}`);if(!t)throw new Error("Need a container to place the button");return this.insertVisaCheckoutButton(t)}insertVisaCheckoutButton(e){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="flex-end",t.innerHTML='\n <img\n alt="Visa Checkout"\n class="v-button"\n role="button"\n src="https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178"\n />\n <a class="v-learn v-learn-default" style="text-align: right; display: block; font-size: 10px; color: #003366;" href="#" data-locale="en_US">Tell Me More</a>',e.appendChild(t),t}}const kt=L(t=>{const i=window,n=new F(t),r=new B(new z(e(),i,n));return new Ot(t,u(),r)},[{id:"braintreevisacheckout"}]);function Et(e){const{billingAddress:t,email:i,firstName:n,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:i,first_name:n,last_name:r,phone_number:o,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}function Tt(e){const{email:t,phone:i,shippingAddress:n}=e,r=(null==n?void 0:n.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:i,address_line_1:null==n?void 0:n.line1,address_line_2:null==n?void 0:n.line2,city:null==n?void 0:n.city,state:null==n?void 0:n.state,country_code:null==n?void 0:n.countryCode,postal_code:null==n?void 0:n.postalCode}}var At=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};const zt=e=>{const{color:t,height:i}=e;return{backgroundColor:(n=t||"",n===re.WHITE?"#FFFFFF":"#3D95CE"),backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:`url("/app/assets/img/payment-providers/venmo-logo-${t===re.WHITE?re.BLUE:re.WHITE}.svg")`,backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:`${i||40}px`,minWidth:"150px",height:"100%",width:"100%",border:t===re.WHITE?"1px solid black":"none"};var n};class Nt{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i,this.onError=o}initialize(e){return At(this,void 0,void 0,function*(){const{braintreevenmo:t,containerId:i,methodId:n}=e;if(!n)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{clientToken:o,initializationData:a}=r,{paymentButtonStyles:s}=a,{cartButtonStyles:d}=s||{},l=(null==t?void 0:t.style)||d;if(!o||!a)throw new U(j.MissingPaymentMethod);if(!i)throw new V('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadDefaultCheckout(),this.onError=(null==t?void 0:t.onError)||this.handleError,this.braintreeSdk.initialize(o);try{const e=yield this.braintreeSdk.getVenmoCheckoutOrThrow();this.renderVenmoButton(e,i,null==t?void 0:t.buyNowInitializeOptions,l)}catch(e){(ge(e)||function(e){return e instanceof N}(e))&&this.handleInitializationVenmoError(e,i)}})}deinitialize(){return At(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}handleError(e){throw new Error(e.message)}createBuyNowCart(e){return At(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=null==e?void 0:e.getBuyNowCartRequestBody();if(!t)throw new U(j.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new pt}}})}handleInitializationVenmoError(e,t){return this.removeVenmoContainer(t),this.onError(e)}removeVenmoContainer(e){const t=document.getElementById(e);t&&t.remove()}renderVenmoButton(e,t,i,n){const r=document.getElementById(t),{color:o}=n||{};if(!r)throw new V("Unable to create wallet button without valid container ID.");r.setAttribute("aria-label","Venmo"),Object.assign(r.style,zt(n||{})),r.addEventListener("click",()=>At(this,void 0,void 0,function*(){r.setAttribute("disabled","true");const t=yield this.createBuyNowCart(i);e.tokenize&&e.tokenize((e,i)=>At(this,void 0,void 0,function*(){r.removeAttribute("disabled"),e&&this.onError(e),yield this.handlePostForm(i,null==t?void 0:t.id)}))})),o===re.BLUE&&(r.addEventListener("mouseenter",()=>{r.style.backgroundColor="#0a7fc2"}),r.addEventListener("mouseleave",()=>{r.style.backgroundColor=zt(n||{}).backgroundColor}))}handlePostForm(e,t){return At(this,void 0,void 0,function*(){const{deviceData:i}=yield this.braintreeSdk.getDataCollectorOrThrow(),{nonce:n,details:r}=e;this.formPoster.postForm("/checkout.php",Object.assign({nonce:n,provider:"braintreevenmo",payment_type:"paypal",device_data:i,action:"set_external_checkout",billing_address:JSON.stringify(Et(r)),shipping_address:JSON.stringify(Tt(r))},t&&{cart_id:t}))})}}const Mt=L(t=>{const i=window,n=e(),r=new F(t),o=new z(n,i,r),a=new B(o);return new Nt(t,u(),a)},[{id:"braintreevenmo"}]);export{K as createBraintreeAchPaymentStrategy,tt as createBraintreeCreditCardPaymentStrategy,ct as createBraintreeFastlaneCustomerStrategy,Ue as createBraintreeFastlanePaymentStrategy,Ne as createBraintreeLocalMethodsPaymentStrategy,wt as createBraintreePaypalButtonStrategy,Pt as createBraintreePaypalCreditButtonStrategy,st as createBraintreePaypalCreditCustomerStrategy,rt as createBraintreePaypalCustomerStrategy,we as createBraintreePaypalPaymentStrategy,Mt as createBraintreeVenmoButtonStrategy,Ge as createBraintreeVenmoPaymentStrategy,kt as createBraintreeVisaCheckoutButtonStrategy,mt as createBraintreeVisaCheckoutCustomerStrategy,We as createBraintreeVisaCheckoutPaymentStrategy};
1
+ import{getScriptLoader as e}from"@bigcommerce/script-loader";import{find as t,isEmpty as i,isEqual as n,isNil as r,noop as o,omit as a,omitBy as s,some as d}from"lodash";import{supportsPopups as l}from"@braintree/browser-detection";import{createRequestSender as c}from"@bigcommerce/request-sender";import{createFormPoster as u}from"@bigcommerce/form-poster";var h,y,m;class p extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class g extends p{constructor(e){super(e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}!function(e){e.Sandbox="sandbox",e.Production="production"}(h||(h={})),function(e){e.Client="client",e.DataCollector="dataCollector",e.Fastlane="fastlane",e.GooglePayment="googlePayment",e.HostedFields="hostedFields",e.LocalPayment="localPayment",e.Paypal="paypal",e.PaypalCheckout="paypalCheckout",e.ThreeDSecure="threeDSecure",e.UsBankAccount="usBankAccount",e.Venmo="venmo",e.VisaCheckout="visaCheckout"}(y||(y={})),function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(m||(m={}));const v="3.128.0",f="3.123.2",b="3.106.0",w={[b]:{[y.Client]:"sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt",[y.PaypalCheckout]:"sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O",[y.Paypal]:"sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+",[y.LocalPayment]:"sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT",[y.DataCollector]:"sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV",[y.UsBankAccount]:"sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ",[y.GooglePayment]:"sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe",[y.ThreeDSecure]:"sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB",[y.VisaCheckout]:"sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT",[y.Venmo]:"sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov",[y.HostedFields]:"sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy",[y.Fastlane]:"sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa"},[f]:{[y.Client]:"sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO",[y.PaypalCheckout]:"sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/",[y.Paypal]:"sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt",[y.LocalPayment]:"sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH",[y.DataCollector]:"sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO",[y.UsBankAccount]:"sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW",[y.GooglePayment]:"sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO",[y.ThreeDSecure]:"sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym",[y.VisaCheckout]:"sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS",[y.Venmo]:"sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU",[y.HostedFields]:"sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P",[y.Fastlane]:"sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y"},[v]:{[y.Client]:"sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq",[y.PaypalCheckout]:"sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh",[y.Paypal]:"sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH",[y.LocalPayment]:"sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC",[y.DataCollector]:"sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc",[y.UsBankAccount]:"sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F",[y.GooglePayment]:"sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i",[y.ThreeDSecure]:"sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D",[y.VisaCheckout]:"sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv",[y.Venmo]:"sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz",[y.HostedFields]:"sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z",[y.Fastlane]:"sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr"}};var C,S,P,I,O,k,E,T,A=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class z{constructor(e,t,i){this.scriptLoader=e,this.braintreeHostWindow=t,this.braintreeSDKVersionManager=i}loadClient(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.Client,"client.min.js")})}loadFastlane(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.Fastlane,"fastlane.min.js")})}loadPaypalCheckout(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.PaypalCheckout,"paypal-checkout.min.js")})}loadPaypal(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.Paypal,"paypal.min.js")})}loadLocalPayment(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.LocalPayment,"local-payment.min.js")})}loadDataCollector(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.DataCollector,"data-collector.min.js")})}loadUsBankAccount(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.UsBankAccount,"us-bank-account.min.js")})}loadGooglePayment(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.GooglePayment,"google-payment.min.js")})}load3DS(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.ThreeDSecure,"three-d-secure.min.js")})}loadVisaCheckout(){return this.loadBraintreeModuleOrThrow(y.VisaCheckout,"visa-checkout.min.js")}loadVenmoCheckout(){return this.loadBraintreeModuleOrThrow(y.Venmo,"venmo.min.js")}loadHostedFields(){return A(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(y.HostedFields,"hosted-fields.min.js")})}loadVisaCheckoutSdk(e){return A(this,void 0,void 0,function*(){if(this.braintreeHostWindow.V)return this.braintreeHostWindow.V;const t=e?"sha384-0eu1s1GtqzXlL9DtLgmwzC5WWlEH/ADRM0n38cVQkvtT+W/gey96rcb1LwuUOPDm":"sha384-1f1csvP3ZFxg4dILH1GaY4LHlZ0oX7Rk83rxmLlwbnIi4TM0NYzXoev1VoEiVDS6";return this.scriptLoader.loadScript(`//${e?"sandbox-":""}assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,{async:!0,attributes:{integrity:t,crossorigin:"anonymous"}}).then(()=>{if(!this.braintreeHostWindow.V)throw new g;return this.braintreeHostWindow.V})})}loadBraintreeModuleOrThrow(e,t){return A(this,void 0,void 0,function*(){let i=this.getBraintreeModule(e);if(i)return i;const n=this.braintreeSDKVersionManager.getSDKVersion(),r=`//js.braintreegateway.com/web/${n}/js/${t}`,o=n in w?this.getIntegrityValuesByModuleName(e,n):void 0;if(yield this.scriptLoader.loadScript(r,o?{async:!0,attributes:{integrity:o,crossorigin:"anonymous"}}:void 0),i=this.getBraintreeModule(e),!i)throw new g;return i})}getBraintreeModule(e){var t;return null===(t=this.braintreeHostWindow.braintree)||void 0===t?void 0:t[e]}getIntegrityValuesByModuleName(e,t){const i=w[t][e];if(!i)throw new Error("Unexpected fileName value");return i}}class N extends p{constructor(e){super(e||"Unsupported browser error"),this.name="UnsupportedBrowserError",this.type="unsupported_browser"}}!function(e){e[e.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",e[e.CustomerNotInitialized=1]="CustomerNotInitialized",e[e.PaymentNotInitialized=2]="PaymentNotInitialized",e[e.ShippingNotInitialized=3]="ShippingNotInitialized",e[e.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(C||(C={}));class M extends p{constructor(e){super(function(e){switch(e){case C.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case C.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case C.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case C.SpamProtectionNotInitialized:return"Unable to proceed because the checkout spam protection has not been initialized.";default:return"Unable to proceed because the required component has not been initialized."}}(e)),this.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}function D(e){return Boolean("object"==typeof e&&null!==e&&("type"in e||"message"in e||"code"in e))}!function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(S||(S={})),function(e){e.Completed="COMPLETED",e.Pending="PENDING",e.Failed="FAILED"}(P||(P={})),function(e){e.TRUSTLY="trustly"}(I||(I={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="cancelled",e.UNRECOGNIZED="unrecognized"}(O||(O={})),function(e){e.Customer="CUSTOMER",e.Merchant="MERCHANT",e.Network="NETWORK",e.Internal="INTERNAL",e.Unknown="UNKNOWN"}(k||(k={})),function(e){e.KountNotEnabled="DATA_COLLECTOR_KOUNT_NOT_ENABLED"}(E||(E={})),function(e){e.Visa="visa",e.Mastercard="mastercard",e.AmericanExpress="american-express",e.DinersClub="diners-club",e.Discover="discover",e.Jcb="jcb",e.UnionPay="union-pay",e.Maestro="maestro",e.Elo="elo",e.Mir="mir",e.Hiper="hiper",e.Hipercard="hipercard"}(T||(T={}));var _=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class B{constructor(e){this.braintreeScriptLoader=e}initialize(e){this.setClientToken(e)}deinitialize(){return _(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollector),this.dataCollector=void 0})}getClient(){return _(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=yield t.create({authorization:e})}return this.client})}getDataCollectorOrThrow(e){return _(this,void 0,void 0,function*(){const t={deviceData:void 0,teardown:()=>Promise.resolve()};if(!this.dataCollector)try{const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadDataCollector(),n=Object.assign({client:t,kount:!0},e);this.dataCollector=yield i.create(n)}catch(e){if(D(e)&&e.code===E.KountNotEnabled)return t;throw e}return this.dataCollector})}getBraintreeGooglePayment(){return _(this,void 0,void 0,function*(){if(!this.googlePayment){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadGooglePayment()]);this.googlePayment=yield t.create({client:e})}return this.googlePayment})}getBraintreeThreeDS(){return _(this,void 0,void 0,function*(){if(!this.threeDS){const[e,t]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]);this.threeDS=yield t.create({client:e,version:2})}return this.threeDS})}getBraintreeLocalPayment(e){return _(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment){const[t,i]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadLocalPayment()]);this.braintreeLocalPayment=yield new Promise((n,r)=>{i.create({client:t,merchantAccountId:e},(e,t)=>{e&&r(e),n(t)})})}return this.braintreeLocalPayment})}getUsBankAccount(){return _(this,void 0,void 0,function*(){if(!this.usBankAccount){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadUsBankAccount();this.usBankAccount=yield t.create({client:e})}return this.usBankAccount})}getBraintreeVisaCheckout(){return this.visaCheckout||(this.visaCheckout=Promise.all([this.getClient(),this.braintreeScriptLoader.loadVisaCheckout()]).then(([e,t])=>t.create({client:e}))),this.visaCheckout}getVisaCheckoutSdk(e){return _(this,void 0,void 0,function*(){return this.visaCheckoutSDK||(this.visaCheckoutSDK=yield this.braintreeScriptLoader.loadVisaCheckoutSdk(e)),this.visaCheckoutSDK})}getVenmoCheckoutOrThrow(){return _(this,void 0,void 0,function*(){if(!this.braintreeVenmo){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadVenmoCheckout(),i={client:e,allowDesktop:!0,paymentMethodUsage:"multi_use"},n=yield t.create(i);if(!n.isBrowserSupported())throw new N;this.braintreeVenmo=n}return this.braintreeVenmo})}setClientToken(e){this.clientToken=e}getClientTokenOrThrow(){if(!this.clientToken)throw new M(C.PaymentNotInitialized);return this.clientToken}teardownModule(e){return e?e.teardown():Promise.resolve()}}function x(e,t,i=!0){var n;return null!==(n=e[t])&&void 0!==n?n:i}class F{constructor(e){this.paymentIntegrationService=e,this.braintreeWindow=window}getSDKVersion(){const e=this.paymentIntegrationService.getState().getStoreConfig(),t=(null==e?void 0:e.checkoutSettings.features)||{};return this.getPreloadedSDKVersion()||(x(t,"PAYPAL-5809.braintree_hosted_fields_fix_version")?v:x(t,"PAYPAL-5636.update_braintree_sdk_version")?f:b)}getPreloadedSDKVersion(){const e=this.braintreeWindow.braintree;if(e){const i=t(Object.values(e),e=>!!e.VERSION);return null==i?void 0:i.VERSION}}}function L(e,t){return Object.assign(e,{resolveIds:t})}class V extends p{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}var j;!function(e){e[e.MissingBillingAddress=0]="MissingBillingAddress",e[e.MissingCart=1]="MissingCart",e[e.MissingCheckout=2]="MissingCheckout",e[e.MissingConsignments=3]="MissingConsignments",e[e.MissingCustomer=4]="MissingCustomer",e[e.MissingCheckoutConfig=5]="MissingCheckoutConfig",e[e.MissingOrder=6]="MissingOrder",e[e.MissingOrderConfig=7]="MissingOrderConfig",e[e.MissingOrderId=8]="MissingOrderId",e[e.MissingPayment=9]="MissingPayment",e[e.MissingPaymentId=10]="MissingPaymentId",e[e.MissingPaymentInstrument=11]="MissingPaymentInstrument",e[e.MissingPaymentMethod=12]="MissingPaymentMethod",e[e.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=14]="MissingPaymentStatus",e[e.MissingPaymentToken=15]="MissingPaymentToken",e[e.MissingShippingAddress=16]="MissingShippingAddress"}(j||(j={}));class U extends p{constructor(e){super(function(e){switch(e){case j.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case j.MissingCart:return"Unable to proceed because cart data is unavailable.";case j.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case j.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case j.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case j.MissingCheckoutConfig:case j.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case j.MissingOrder:return"Unable to proceed because order data is unavailable.";case j.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case j.MissingPayment:return"Unable to proceed because payment data is unavailable.";case j.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case j.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case j.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e)),this.subtype=e,this.name="MissingDataError",this.type="missing_data"}}class R extends V{constructor(e){let t="Unable to submit payment for the order because the payload is invalid.";e&&(t=`${t} Make sure the following fields are provided correctly: ${e.join(", ")}.`),super(t),this.name="PaymentArgumentInvalidError"}}function H(e){return Boolean(e.instrumentId)}class W extends p{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}function q(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}class $ extends p{constructor(e){super(e||"Unable to proceed because the client library of a payment method has thrown an unexpected error."),this.name="PaymentMethodFailedError",this.type="payment_method_client_invalid"}}function G(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var Y=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class J{constructor(e,t){this.paymentIntegrationService=e,this.braintreeSdk=t}initialize(e){return Y(this,void 0,void 0,function*(){const{methodId:t,braintreeach:i}=e||{};if(!t)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');this.getMandateText=null==i?void 0:i.getMandateText,yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{clientToken:r,initializationData:o}=n;if(!r||!o)throw new U(j.MissingPaymentMethod);this.braintreeSdk.initialize(r);try{this.usBankAccount=yield this.braintreeSdk.getUsBankAccount()}catch(e){this.handleBraintreeError(e)}})}execute(e,t){return Y(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new R(["payment"]);const r=H(i.paymentData||{}),o=r?yield this.tokenizePaymentForVaultedInstrument(i):yield this.tokenizePayment(i),a=r?yield this.preparePaymentDataForVaultedInstrument(o,i):yield this.preparePaymentData(o,i);yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new W)}deinitialize(){return Y(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}tokenizePayment({paymentData:e}){return Y(this,void 0,void 0,function*(){const t=this.getUsBankAccountOrThrow();if(!G(e))throw new R(["payment.paymentData"]);const i=H(e)?"The data are used for stored instrument verification":"function"==typeof this.getMandateText&&this.getMandateText();if(!i)throw new V("Unable to proceed because getMandateText is not provided or returned undefined value.");try{const{nonce:n}=yield t.tokenize({bankDetails:this.getBankDetails(e),mandateText:i});return n}catch(e){this.handleBraintreeError(e)}})}tokenizePaymentForVaultedInstrument(e){return Y(this,void 0,void 0,function*(){const{methodId:t,paymentData:i={}}=e,n=this.paymentIntegrationService.getState(),{config:r}=n.getPaymentMethodOrThrow(t);if(!r.isVaultingEnabled)throw new V("Vaulting is disabled but a vaulted instrument was being used for this transaction");return G(i)?this.tokenizePayment(e):null})}preparePaymentData(e,t){return Y(this,void 0,void 0,function*(){const{methodId:i,paymentData:n={}}=t;if(!G(n))throw new R(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,routingNumber:s,accountNumber:d}=n;return{methodId:i,paymentData:{deviceSessionId:r,shouldSetAsDefaultInstrument:a,shouldSaveInstrument:o,formattedPayload:{tokenized_bank_account:{issuer:s,masked_account_number:d.substr(-4),token:e}}}}})}preparePaymentDataForVaultedInstrument(e,t){return Y(this,void 0,void 0,function*(){const{methodId:i,paymentData:n={}}=t;if(!H(n)||!q(n))throw new R(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{instrumentId:o,shouldSetAsDefaultInstrument:a}=n;return{methodId:i,paymentData:Object.assign({deviceSessionId:r,instrumentId:o,shouldSetAsDefaultInstrument:a},e&&{nonce:e})}})}getBankDetails(e){const t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i=e.ownershipType.toLowerCase(),n=e.accountType.toLowerCase();return Object.assign(Object.assign({accountNumber:e.accountNumber,routingNumber:e.routingNumber,ownershipType:i},"personal"===i?{firstName:e.firstName,lastName:e.lastName}:{businessName:e.businessName}),{accountType:n,billingAddress:{streetAddress:t.address1,extendedAddress:t.address2,locality:t.city,region:t.stateOrProvinceCode,postalCode:t.postalCode}})}getUsBankAccountOrThrow(){if(!this.usBankAccount)throw new M(C.PaymentNotInitialized);return this.usBankAccount}handleBraintreeError(e){if(!D(e))throw e;throw new $(e.message)}}const K=L(t=>new J(t,(t=>{const i=new F(t),n=new z(e(),window,i);return new B(n)})(t)),[{id:"braintreeach"}]);class X extends p{constructor(e,t){super(t||"Unable to proceed because the payment form contains invalid data."),this.details=e,this.name="PaymentInvalidFormError",this.type="payment_invalid_form"}}class Q extends p{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}class Z{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}let ee=null;const te=["buttons","messages"];var ie,ne,re,oe,ae,se;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(ie||(ie={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(ne||(ne={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(re||(re={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(oe||(oe={})),function(e){e.PILL="pill",e.RECT="rect"}(ae||(ae={})),function(e){e.CART="cart",e.HOME="homepage",e.PAYMENT="payment",e.PRODUCT="product"}(se||(se={}));var de=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class le{constructor(e,t,i){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.overlay=i,this.dataCollectors={}}initialize(e,t){this.clientToken=e,this.threeDSecureOptions=t}getBraintreeFastlane(e,t,i){return de(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("axoEnv","sandbox"),window.localStorage.setItem("fastlaneEnv","sandbox")),!this.braintreeHostWindow.braintreeFastlane){const t=this.getClientTokenOrThrow(),n=yield this.getClient(),r=yield this.getSessionId(e),o=yield this.braintreeScriptLoader.loadFastlane(),a={root:{backgroundColorPrimary:"transparent"}};this.braintreeHostWindow.braintreeFastlane=yield o.create({authorization:t,client:n,deviceData:r,styles:i||a})}return this.braintreeHostWindow.braintreeFastlane})}getClient(){return de(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=t.create({authorization:e})}return this.client})}getPaypal(){return this.braintreePaypal||(this.braintreePaypal=Promise.all([this.getClient(),this.braintreeScriptLoader.loadPaypal()]).then(([e,t])=>t.create({client:e}))),this.braintreePaypal}paypal(e){var{shouldSaveInstrument:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["shouldSaveInstrument"]);const n=l();return this.getPaypal().then(e=>{var r;return n&&(null===(r=this.overlay)||void 0===r||r.show({onClick:()=>e.focusWindow()})),e.tokenize(Object.assign({enableShippingAddress:!0,flow:t?"vault":"checkout",useraction:"commit"},i))}).then(e=>{var t;return null===(t=this.overlay)||void 0===t||t.remove(),e}).catch(e=>{var t;throw null===(t=this.overlay)||void 0===t||t.remove(),e})}getPaypalCheckout(e,t,i){return de(this,void 0,void 0,function*(){const n=yield this.getClient(),r=yield this.braintreeScriptLoader.loadPaypalCheckout(),o={client:n};return this.paypalCheckout=yield r.create(o,(n,r)=>{var o;if(n)return i(n);const a=Object.assign(Object.assign({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:te.toString(),intent:e.intent,commit:null===(o=e.commit)||void 0===o||o});this.braintreeHostWindow.paypal?t(r):function(e,t){return ee||(ee=new Promise((i,n)=>{e.loadPayPalSDK(t,t=>{t?(ee=null,n(t)):i(e)})})),ee}(r,a).then(()=>t(r))}),this.paypalCheckout})}getDataCollector(e){return de(this,void 0,void 0,function*(){const t=(null==e?void 0:e.paypal)?"paypal":"default";let i=this.dataCollectors[t];if(!i){try{const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadDataCollector(),r=Object.assign({client:t,kount:!0},e);i=yield n.create(r)}catch(e){if(!D(e)||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==e.code)throw e;i={deviceData:void 0,teardown:()=>Promise.resolve()}}this.dataCollectors[t]=i}return i})}getBraintreeEnv(e=!1){return e?h.Sandbox:h.Production}mapToBraintreeShippingAddressOverride(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}mapToLegacyShippingAddress(e){const{email:t,phone:i,shippingAddress:n}=e,r=(null==n?void 0:n.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:i,address_line_1:null==n?void 0:n.line1,address_line_2:null==n?void 0:n.line2,city:null==n?void 0:n.city,state:null==n?void 0:n.state,country_code:null==n?void 0:n.countryCode,postal_code:null==n?void 0:n.postalCode}}mapToLegacyBillingAddress(e){const{billingAddress:t,email:i,firstName:n,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:i,first_name:n,last_name:r,phone_number:o,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}getSessionId(e){return de(this,void 0,void 0,function*(){const{deviceData:t}=yield this.getDataCollector({riskCorrelationId:e});return t})}teardown(){return de(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollectors.default),yield this.teardownModule(this.dataCollectors.paypal),this.dataCollectors={},yield this.teardownModule(this.paypalCheckout),this.paypalCheckout=void 0})}get3DS(){return de(this,void 0,void 0,function*(){return this.threeDS||(this.threeDS=Promise.all([this.getClient(),this.braintreeScriptLoader.load3DS()]).then(([e,t])=>t.create({client:e,version:2}))),this.threeDS})}getVenmoCheckout(e){return de(this,void 0,void 0,function*(){if(!this.venmoCheckout){const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadVenmoCheckout(),n=Object.assign({client:t,allowDesktop:!0,paymentMethodUsage:"multi_use"},e||{});this.venmoCheckout=yield new Promise((e,t)=>{i.create(n,(i,n)=>i?t(i):n.isBrowserSupported()?void e(n):t(new N))})}return this.venmoCheckout})}verifyCard(e,t,i){return de(this,void 0,void 0,function*(){const n=yield this.tokenizeCard(e,t);return this.challenge3DSVerification(n,i)})}tokenizeCard(e,t){return de(this,void 0,void 0,function*(){const{paymentData:n}=e;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"object"==typeof t.ccExpiry&&null!==t.ccExpiry&&"string"==typeof t.ccNumber&&"string"==typeof t.ccName}(n))throw new R(["payment.paymentData"]);const r=this.getErrorsRequiredFields(n);if(!i(r))throw new X(r);const o=this.mapToCreditCard(n,t),a=yield this.getClient(),{creditCards:s}=yield a.request(o);return{nonce:s[0].nonce,bin:s[0].details.bin}})}challenge3DSVerification(e,t){return de(this,void 0,void 0,function*(){const i=yield this.get3DS();return this.present3DSChallenge(i,t,e)})}teardownModule(e){return e?e.teardown():Promise.resolve()}getClientTokenOrThrow(){if(!this.clientToken)throw new M(C.PaymentNotInitialized);return this.clientToken}getErrorsRequiredFields(e){const{ccNumber:t,ccExpiry:i}=e,n={};return t||(n.ccNumber=[{message:"Credit card number is required",type:"required"}]),i||(n.ccExpiry=[{message:"Expiration date is required",type:"required"}]),n}mapToCreditCard(e,t){return{data:{creditCard:{cardholderName:e.ccName,number:e.ccNumber,cvv:e.ccCvv,expirationDate:`${e.ccExpiry.month}/${e.ccExpiry.year}`,options:{validate:!1},billingAddress:t&&{countryCodeAlpha2:t.countryCode,locality:t.city,countryName:t.country,postalCode:t.postalCode,streetAddress:t.address2?`${t.address1} ${t.address2}`:t.address1}}},endpoint:"payment_methods/credit_cards",method:"post"}}present3DSChallenge(e,t,i){const{nonce:n,bin:r}=i;if(!this.threeDSecureOptions||!n)throw new M(C.PaymentNotInitialized);const{addFrame:o,removeFrame:a,challengeRequested:s=!0,additionalInformation:d}=this.threeDSecureOptions,l=()=>de(this,void 0,void 0,function*(){const t=yield e.cancelVerifyCard();return u.cancel(new Q),t}),c=t.toFixed(2),u=new Z(e.verifyCard({addFrame:(e,t)=>{o&&o(e,t,l)},amount:Number(c),bin:r,challengeRequested:s,nonce:n,removeFrame:a,onLookupComplete:(e,t)=>{t()},collectDeviceData:!0,additionalInformation:d}));return u.promise}}class ce{constructor(e){this.paymentIntegrationService=e,this.braintreeHostWindow=window}render(e,t,i){const n=t&&document.getElementById(t);if(this.braintreeHostWindow.paypal&&n){const r=this.paymentIntegrationService.getState(),o=r.getCartOrThrow(),a=r.getBillingAddressOrThrow(),s=r.getPaymentMethodOrThrow(e);if(!s.initializationData)return;const{paypalBNPLConfiguration:d=[]}=s.initializationData,l=i===se.PAYMENT?"checkout":i,c=d&&d.find(({id:e})=>e===l);if(!c||!c.status)return;i===se.CART&&(n.removeAttribute("data-pp-style-logo-type"),n.removeAttribute("data-pp-style-logo-position"),n.removeAttribute("data-pp-style-text-color"),n.removeAttribute("data-pp-style-text-size")),this.braintreeHostWindow.paypal.Messages({amount:o.cartAmount,buyerCountry:a.countryCode,placement:i,style:this.getPaypalMessagesStylesFromBNPLConfig(c)}).render(`#${t}`)}}getPaypalMessagesStylesFromBNPLConfig({styles:e}){const t={};return e.color&&(t.color=e.color),e.layout&&(t.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(t.logo={},e["logo-type"]&&(t.logo.type=e["logo-type"]),e["logo-position"]&&(t.logo.position=e["logo-position"])),e.ratio&&(t.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(t.text={},e["text-color"]&&(t.text.color=e["text-color"]),e["text-size"]&&(t.text.size=+e["text-size"])),t}}class ue{constructor(e){const{element:t,closeElement:i,mainElement:n}=this._createElements(e);this._element=t,this._closeElement=i,this._mainElement=n}show(e){this._mainElement.parentElement||(this._registerClick(e),document.body.appendChild(this._mainElement),setTimeout(()=>this._element.style.opacity="1"))}remove(){this._mainElement.parentElement&&(this._unregisterClick&&this._unregisterClick(),this._removeAfterTransition(),setTimeout(()=>this._element.style.opacity="0"))}_createElements(e){const t=document.createElement("div"),{background:i="rgba(0, 0, 0, 0.8)",id:n="checkoutOverlay",transitionDuration:r=400,hasCloseButton:o=!1,innerHtml:a=null}=e||{};let s,d,l,c,u=t;if(n&&(t.id=n),a){const e=document.createElement("div");c=`${n}--overlayText`,e.className=c,e.appendChild(a),t.appendChild(e)}return o&&(l=`${n}--close`,s=document.createElement("div"),s.className=l,d=`${n}--layout`,u=document.createElement("div"),u.className=d,u.appendChild(t),u.appendChild(s)),u.appendChild(function(e){const{id:t,background:i,transitionDuration:n,classLayout:r,classOverlayText:o,classClose:a}=e,s=document.createElement("style"),d=r?`, .${r}`:"";return s.id=`${t}--styles`,s.type="text/css",s.innerText=`\n #${t}${d} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${t} {\n transition: opacity ${n}ms ease-out;\n background: ${i};\n opacity: 0;\n }\n `,o&&(s.innerText+=`\n #${t} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${t} .${o} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `),a&&(s.innerText+=`\n #${t} {\n opacity: 1;\n }\n .${r} .${a} {\n position: fixed;\n right: 16px;\n top: 16px;\n width: 16px;\n height: 16px;\n opacity: 0.6;\n cursor: pointer;\n z-index: 3147483647;\n }\n .${r} .${a}::after, .${r} .${a}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${r} .${a}::after {\n transform: rotate(-45deg);\n }\n .${r} .${a}::before {\n transform: rotate(45deg);\n }\n `),s}({id:n,background:i,transitionDuration:r,classLayout:d,classOverlayText:c,classClose:l})),{element:t,closeElement:s,mainElement:u}}_addEventListener(e,t){e&&t&&e.addEventListener("click",t)}_removeEventListener(e,t){e&&t&&e.removeEventListener("click",t)}_registerClick(e){if(this._unregisterClick&&this._unregisterClick(),e){const{onClick:t,onClickClose:i}=e;this._addEventListener(this._element,t),this._addEventListener(this._closeElement,i),this._unregisterClick=()=>{this._removeEventListener(this._element,t),this._removeEventListener(this._closeElement,i),this._unregisterClick=void 0}}}_removeAfterTransition(){const e=t=>{"opacity"===t.propertyName&&(this._mainElement.parentElement&&this._mainElement.remove(),this._element.removeEventListener("transitionend",e))};this._element.addEventListener("transitionend",e)}}const he={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},ye="embedded-checkout-loading-indicator-rotation";class me{constructor(e){this.styles=Object.assign(Object.assign({},he),e&&e.styles),this.containerStyles=Object.assign({},e&&e.containerStyles),this.defineAnimation(),this.container=this.buildContainer(),this.indicator=this.buildIndicator(),this.container.appendChild(this.indicator)}show(e){if(e){const t=document.getElementById(e);if(!t)throw new Error("Unable to attach the loading indicator because the parent ID is not valid.");t.appendChild(this.container)}this.container.style.visibility="visible",this.container.style.opacity="1"}hide(){const e=()=>{this.container.style.visibility="hidden",this.container.removeEventListener("transitionend",e)};this.container.addEventListener("transitionend",e),this.container.style.opacity="0"}buildContainer(){const e=document.createElement("div");return e.style.display="block",e.style.bottom="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.position="absolute",e.style.right="0",e.style.top="0",e.style.transition="all 250ms ease-out",e.style.opacity="0",this.setStyleAttribute(e,this.containerStyles),e}buildIndicator(){const e=document.createElement("div");return e.style.display="block",e.style.width=`${this.styles.size}px`,e.style.height=`${this.styles.size}px`,e.style.borderRadius=`${this.styles.size}px`,e.style.border="solid 1px",e.style.borderColor=`${this.styles.backgroundColor} ${this.styles.backgroundColor} ${this.styles.color} ${this.styles.color}`,e.style.margin="0 auto",e.style.position="absolute",e.style.left="0",e.style.right="0",e.style.top="50%",e.style.transform="translateY(-50%) rotate(0deg)",e.style.transformStyle="preserve-3d",e.style.animation=`${ye} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])})}defineAnimation(){var e;if(document.getElementById(ye))return;const t=document.createElement("style");t.id=ye,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${ye} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}const pe={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};function ge(e){return"object"==typeof e&&null!==e&&"name"in e&&"BraintreeError"===e.name}function ve(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}var fe=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class be{constructor(e,t,i,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeMessages=i,this.loadingIndicator=n,this.braintreeHostWindow=window}initialize(e){return fe(this,void 0,void 0,function*(){const{braintree:t,methodId:i}=e;if(this.braintree=t,this.paymentMethod&&this.paymentMethod.nonce||(this.paymentMethod=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i)),this.paymentMethod.clientToken&&(null==t?void 0:t.bannerContainerId))return yield this.loadPaypal(),this.loadPaypalCheckoutInstance();if(this.paymentMethod.clientToken)return this.loadPaypal();const n=yield this.paymentIntegrationService.loadPaymentMethod(i);if(this.paymentMethod=n.getPaymentMethodOrThrow(i),null==t?void 0:t.bannerContainerId)return this.loadPaypalCheckoutInstance();if(!this.paymentMethod.clientToken)throw new U(j.MissingPaymentMethod);return this.loadPaypal()})}execute(e,t){var i;return fe(this,void 0,void 0,function*(){const{payment:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{onError:o}=this.braintree||{};if(!n)throw new R(["payment"]);try{const e=yield this.preparePaymentData(n,r.useStoreCredit);yield this.paymentIntegrationService.submitOrder(r,t),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.isProviderError(e)&&(yield this.loadPaypal(),null===(i=this.paypalButtonRender)||void 0===i||i.close(),yield this.loadPaypalCheckoutInstance(),yield new Promise((e,t)=>{o&&"function"==typeof o&&o(new Error("INSTRUMENT_DECLINED")),t()})),this.handleError(e)}})}finalize(){return Promise.reject(new W)}deinitialize(){var e;return this.braintreeTokenizePayload=void 0,null===(e=this.paypalButtonRender)||void 0===e||e.close(),this.braintreeIntegrationService.teardown()}preparePaymentData(e,t){var i;return fe(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),r=n.getOutstandingBalance(t),o=n.getStoreConfig();if(!r)throw new U(j.MissingCheckout);if(!o)throw new U(j.MissingCheckoutConfig);if(!this.paymentMethod)throw new M(C.PaymentNotInitialized);const{currency:a,storeProfile:{storeLanguage:s}}=o,{nonce:d,config:{isVaultingEnabled:l}}=this.paymentMethod,{methodId:c,paymentData:u={}}=e,h=(null===(i=this.braintreeTokenizePayload)||void 0===i?void 0:i.nonce)||d;if(h){const t=yield this.paymentIntegrationService.loadPaymentMethod(c);return this.paymentMethod=t.getPaymentMethod(c),Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(h)})}if(H(u)||(y=u,Boolean(y.instrumentId)&&!Object.prototype.hasOwnProperty.call(y,"ccNumber")&&!Object.prototype.hasOwnProperty.call(y,"ccCvv"))){if(!l)throw new V("Vaulting is disabled but a vaulted instrument was being used for this transaction");return Promise.resolve(e)}var y;if(!q(u))throw new U(j.MissingPayment);const{shouldSaveInstrument:m,shouldSetAsDefaultInstrument:p}=u;if(m&&!l)throw new V("Vaulting is disabled but shouldSaveInstrument is set to true");const g=n.getShippingAddress(),v=g?ve(g):void 0;return Promise.all([this.braintreeIntegrationService.paypal({amount:r,locale:s,currency:a.code,offerCredit:"braintreepaypalcredit"===this.paymentMethod.id,shippingAddressOverride:v,shouldSaveInstrument:m||!1,shippingAddressEditable:!1}),this.braintreeIntegrationService.getSessionId()]).then(([{nonce:t,details:i}={},n])=>Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(t,i&&i.email,n,m,p)}))})}formattedPayload(e,t,i,n,r){return{formattedPayload:{vault_payment_instrument:n||null,set_as_default_stored_instrument:r||null,device_info:i||null,paypal_account:{token:e,email:t||null}}}}loadPaypalCheckoutInstance(){return fe(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t,id:i}=this.paymentMethod||{};if(!e)throw new U(j.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e);const n={currency:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,intent:null==t?void 0:t.intent,isCreditEnabled:null==t?void 0:t.isCreditEnabled},r="braintreepaypalcredit"===i||!(null==t?void 0:t.isCreditEnabled);yield this.braintreeIntegrationService.getPaypalCheckout(n,e=>{var t;r&&i&&(null===(t=this.braintree)||void 0===t?void 0:t.bannerContainerId)&&this.renderPayPalMessages(i,this.braintree.bannerContainerId),this.renderPayPalButton(e)},this.handleError)}catch(e){this.handleError(e)}})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,se.PAYMENT)}renderPayPalButton(e){const{onPaymentError:t,submitForm:i,onRenderButton:n,containerId:r,onError:o}=this.braintree||{};if(!r)return;if(!this.paymentMethod)throw new M(C.PaymentNotInitialized);this.loadingIndicatorContainer=r.split("#")[1];const{id:a,config:{testMode:s}}=this.paymentMethod,{paypal:d}=this.braintreeHostWindow,l=null==d?void 0:d.FUNDING.PAYPAL;d&&l?(this.paypalButtonRender=d.Buttons({env:s?"sandbox":"production",commit:!1,fundingSource:l,onClick:()=>{this.toggleLoadingIndicator(!0)},createOrder:()=>this.setupPayment(e,a,t),onApprove:t=>fe(this,void 0,void 0,function*(){this.braintreeTokenizePayload=yield this.tokenizePaymentOrThrow(t,e),i&&"function"==typeof i&&i()}),onCancel:()=>{this.toggleLoadingIndicator(!1)},onError:e=>{this.toggleLoadingIndicator(!1),null==o||o(e)}}),n&&"function"==typeof n&&n(),this.paypalButtonRender.isEligible()&&this.paypalButtonRender.render(`${r}`)):this.removeElement(r.split("#")[1])}setupPayment(e,t,i){return fe(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState();try{const i=n.getCustomer(),r=n.getPaymentMethodOrThrow(t),o=n.getCheckoutOrThrow().outstandingBalance,a=n.getStoreConfigOrThrow().currency.code,s=n.getShippingAddress()||(null==i?void 0:i.addresses[0]),d=s?ve(s):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:d,amount:o,currency:a,offerCredit:!1,intent:r.initializationData.intent})}catch(e){throw i&&(ge(e)||e instanceof p)&&i(e),e}})}tokenizePaymentOrThrow(e,t,i){return fe(this,void 0,void 0,function*(){try{return yield t.tokenizePayment(e)}catch(e){throw i&&(ge(e)||e instanceof p)&&i(e),e}})}loadPaypal(){return fe(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t}=this.paymentMethod||{};if(!e||!t)throw new U(j.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e),yield this.braintreeIntegrationService.getPaypal()}catch(e){this.handleError(e)}return Promise.resolve()})}handleError(e){if(!ge(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Q(e.message);throw new $(e.message)}isProviderError(e){var t,i,n;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"2046"===(null===(n=null===(i=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===i?void 0:i.provider_error)||void 0===n?void 0:n.code)}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const we=L(t=>{const i=window,n=new ue,r=new F(t),o=new le(new z(e(),i,r),i,n),a=new ce(t);return new be(t,o,a,new me({containerStyles:pe}))},[{id:"braintreepaypal"},{id:"braintreepaypalcredit"}]);var Ce;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(Ce||(Ce={}));const Se=Ce,Pe={"X-Checkout-SDK-Version":"1.858.0"};class Ie{constructor(e){this.requestSender=e}getOrderStatus(e="braintreelocalmethods",t){return i=this,n=void 0,o=function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":"This API endpoint is for internal use only and may change in the future","Content-Type":Se.Json},Pe);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}const Oe={body:{},headers:{},status:0};class ke extends p{constructor(e,{message:t,errors:i}={}){const{body:n,headers:r,status:o}=e||Oe;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=n,this.headers=r,this.status=o,this.errors=i||[]}}class Ee extends ke{constructor(e){super(e,{message:"There is a problem processing your payment. Please try again later."}),this.name="PaymentMethodInvalidError",this.type="payment_method_invalid"}}class Te extends ke{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var Ae=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ze{constructor(e,t,i,n,r=3e3,a=3e5){this.paymentIntegrationService=e,this.braintreeSdk=t,this.braintreeRequestSender=i,this.loadingIndicator=n,this.pollingInterval=r,this.maxPollingIntervalTime=a,this.isLPMsUpdateExperimentEnabled=!1,this.pollingTimer=0,this.stopPolling=o,this.isPollingEnabled=!1}initialize(e){return Ae(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,braintreelocalmethods:n}=e;if(this.gatewayId=t,!i)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new V('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new V('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');this.braintreelocalmethods=n,this.loadingIndicatorContainer=n.container.split("#")[1],yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(t),{clientToken:a,config:s,initializationData:d}=o,l=r.getStoreConfigOrThrow().checkoutSettings.features;if(this.isPollingEnabled=x(l,"PAYPAL-5258.braintree_local_methods_polling"),this.isLPMsUpdateExperimentEnabled=x(l,"PAYPAL-4853.add_new_payment_flow_for_braintree_lpms"),!a||!d||!s.merchantId)throw new U(j.MissingPaymentMethod);try{this.braintreeSdk.initialize(a),this.isNonInstantPaymentMethod(i)||(this.braintreeLocalPayment=yield this.braintreeSdk.getBraintreeLocalPayment(s.merchantId))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new W)}deinitialize(){return Ae(this,void 0,void 0,function*(){return this.toggleLoadingIndicator(!1),Promise.resolve()})}execute(e,t){return Ae(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new R(["payment"]);const{methodId:r}=i;this.toggleLoadingIndicator(!0),this.isNonInstantPaymentMethod(r)?yield this.executeWithNotInstantLPM(r):yield this.executeWithInstantLPM(r,n,t)})}executeWithNotInstantLPM(e){return Ae(this,void 0,void 0,function*(){try{const t=yield this.getLPMsBasicPaymentData();yield this.paymentIntegrationService.submitOrder(),yield this.paymentIntegrationService.submitPayment({methodId:e,paymentData:Object.assign(Object.assign({},t),{formattedPayload:{method:e}})})}catch(e){if(this.isBraintreeRedirectError(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise((e,i)=>{window.location.replace(t),this.toggleLoadingIndicator(!1),i()})}return this.handleError(e),Promise.reject(e)}})}executeWithInstantLPM(e,t,i){return Ae(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment)throw new Ee;yield new Promise((n,r)=>{var o;null===(o=this.braintreeLocalPayment)||void 0===o||o.startPayment(this.getInstantLPMConfig(e,t,i),this.getInstantLPMCallback(n,r,e,t,i))})})}getLPMsBasicPaymentData(){return Ae(this,void 0,void 0,function*(){const{deviceData:e}=yield this.braintreeSdk.getDataCollectorOrThrow();return{deviceSessionId:e}})}getInstantLPMConfig(e,t,i){const n=this.paymentIntegrationService.getState(),r=n.getCartOrThrow(),o=n.getBillingAddressOrThrow(),{firstName:a,lastName:s,countryCode:d}=o,{currency:l,email:c,lineItems:u}=r,h=u.physicalItems.length>0,y=n.getCheckoutOrThrow().outstandingBalance,m=n.getStoreConfigOrThrow().links.checkoutLink;return{paymentType:e,amount:y,fallback:{url:m,buttonText:"Complete Payment"},currencyCode:l.code,shippingAddressRequired:h,email:c,givenName:a,surname:s,address:{countryCode:d},onPaymentStart:(n,r)=>Ae(this,void 0,void 0,function*(){if(!this.isLPMsUpdateExperimentEnabled)return this.orderId=n.paymentId,void r();const o=yield this.getLPMsBasicPaymentData(),a=Object.assign(Object.assign({},o),{formattedPayload:{method:e,[`${e}_account`]:{order_id:n.paymentId}}});try{yield this.paymentIntegrationService.submitOrder(t,i),yield this.paymentIntegrationService.submitPayment({methodId:e,paymentData:a})}catch(t){if(this.isBraintreeOrderSavedResponse(t)&&t.body.additional_action_required.data.order_id_saved_successfully)return r(),this.isPollingEnabled?new Promise((t,i)=>{this.initializePollingMechanism(e,t,i,this.gatewayId)}):void 0;throw t}})}}getInstantLPMCallback(e,t,i,n,r){const o=this.paymentIntegrationService.getState().getCartOrThrow();return(a,s)=>Ae(this,void 0,void 0,function*(){if(a)return"LOCAL_PAYMENT_WINDOW_CLOSED"===a.code?(this.toggleLoadingIndicator(!1),this.resetPollingMechanism(),t()):(this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t(new Ee));const d=yield this.getLPMsBasicPaymentData(),l=Object.assign(Object.assign({},d),{formattedPayload:{method:i,[`${i}_account`]:Object.assign({email:o.email,token:s.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId})}});try{return this.isLPMsUpdateExperimentEnabled||(yield this.paymentIntegrationService.submitOrder(n,r)),yield this.paymentIntegrationService.submitPayment({methodId:i,paymentData:l}),e(void 0)}catch(e){return this.handleError(e),t(e)}})}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}handleError(e){const{onError:t}=this.braintreelocalmethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}isNonInstantPaymentMethod(e){return e.toUpperCase()in I}isBraintreeRedirectError(e){var t;if("object"!=typeof e||null===e)return!1;const{body:i}=e;return!!i&&!!(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}isBraintreeOrderSavedResponse(e){var t;if("object"!=typeof e||null===e)return!1;const{body:i}=e;return!!i&&(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.hasOwnProperty("order_id_saved_successfully"))}initializePollingMechanism(e,t,i,n){return Ae(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.braintreeRequestSender.getOrderStatus(n,{params:{useMetadata:!1}}),o=r.status===P.Pending,a=r.status===P.Completed,s=r.status===P.Failed;if(a)return this.deinitializePollingMechanism(),t();if(s)return i();if(!a&&o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,braintreelocalmethods:this.braintreelocalmethods}),this.handleError(new Te)}catch(e){i()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}reinitializeStrategy(e){return Ae(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}}const Ne=L(t=>{const i=window,n=new F(t),r=new B(new z(e(),i,n)),o=c(),a=new Ie(o);return new ze(t,r,a,new me({styles:{backgroundColor:"black"}}))},[{gateway:"braintreelocalmethods"}]);function Me(e){return"string"!=typeof e}function De(e,t){if(t||e)return function(e){var t,i;const n={},r=s(e.root,Me),o=s(e.input,Me),a=s(e.toggle,Me),d=s(null===(t=e.text)||void 0===t?void 0:t.body,Me),l=s(null===(i=e.text)||void 0===i?void 0:i.caption,Me),c=e.branding;return Object.keys(r).length&&(n.root=r),Object.keys(o).length&&(n.input=o),Object.keys(a).length&&(n.toggle=a),Object.keys(d).length&&(n.text={},n.text.body=d),Object.keys(l).length&&(n.text=Object.assign({},n.text),n.text.caption=l),c&&(n.branding=c),n}(function(e,t){var i,n,r,o,a,s,d,l,c,u,h,y,m,p,g,v,f,b,w,C,S,P;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(c=null==t?void 0:t.input)||void 0===c?void 0:c.focusBorderColor),backgroundColor:(null==e?void 0:e.fastlaneInputSettingsBackgroundColor)||(null===(u=null==t?void 0:t.input)||void 0===u?void 0:u.backgroundColor),borderWidth:(null==e?void 0:e.fastlaneInputSettingsBorderWidth)||(null===(h=null==t?void 0:t.input)||void 0===h?void 0:h.borderWidth),textColorBase:(null==e?void 0:e.fastlaneInputSettingsTextColorBase)||(null===(y=null==t?void 0:t.input)||void 0===y?void 0:y.textColorBase)},toggle:{colorPrimary:(null==e?void 0:e.fastlaneToggleSettingsColorPrimary)||(null===(m=null==t?void 0:t.toggle)||void 0===m?void 0:m.colorPrimary),colorSecondary:(null==e?void 0:e.fastlaneToggleSettingsColorSecondary)||(null===(p=null==t?void 0:t.toggle)||void 0===p?void 0:p.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(b=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===b?void 0:b.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(C=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===C?void 0:C.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(P=null===(S=null==t?void 0:t.text)||void 0===S?void 0:S.caption)||void 0===P?void 0:P.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}function _e(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var Be,xe=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Fe{constructor(e,t,i){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.braintreeSdk=i}initialize(e){var t;return xe(this,void 0,void 0,function*(){const{methodId:i,braintreefastlane:n}=e;if(!i)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new V('Unable to initialize payment because "options.braintreefastlane" argument is not provided.');if(!n.onInit||"function"!=typeof n.onInit)throw new V('Unable to initialize payment because "options.braintreefastlane.onInit" argument is not provided or it is not a function.');if(!n.onChange||"function"!=typeof n.onChange)throw new V('Unable to initialize payment because "options.braintreefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(i),{initializationData:a,clientToken:s}=o||{},{isFastlaneStylingEnabled:d}=a||{},l=x(r.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");this.is3DSEnabled=o.config.is3dsEnabled,s&&l&&this.braintreeSdk.initialize(s);const c=De(d?null===(t=o.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,n.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(i,c),this.shouldRunAuthenticationFlow()&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow()),yield this.initializeCardComponent(),this.onError=n.onError,n.onInit(e=>this.renderBraintreeCardComponent(e)),n.onChange(()=>this.handleBraintreeStoredInstrumentChange(i))})}execute(e,t){return xe(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new R(["payment"]);yield this.paymentIntegrationService.submitOrder(n,t);const r=yield this.preparePaymentPayload(i.methodId);yield this.paymentIntegrationService.submitPayment(r),this.braintreeFastlaneUtils.removeSessionIdFromCookies()})}finalize(){return Promise.reject(new W)}deinitialize(){return xe(this,void 0,void 0,function*(){return this.braintreeCardComponent=void 0,Promise.resolve()})}initializeCardComponent(){return xe(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),{phone:t,firstName:i,lastName:n}=e.getBillingAddressOrThrow(),r=`${i} ${n}`,o={styles:{},fields:Object.assign({cardholderName:{prefill:r,enabled:!0}},t&&{phoneNumber:{prefill:t}})},a=this.braintreeFastlaneUtils.getBraintreeFastlaneComponentOrThrow();this.braintreeCardComponent=yield a(o)})}renderBraintreeCardComponent(e){const t=this.getBraintreeCardComponentOrThrow();if(!e)throw new V('Unable to initialize payment because "container" argument is not provided.');t.render(e)}preparePaymentPayload(e){var t,i;return xe(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),r=n.getBillingAddressOrThrow(),o=`${r.firstName} ${r.lastName}`,a=this.getPayPalInstruments()[0],s=yield this.braintreeFastlaneUtils.getDeviceSessionId(),d=x(n.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");if(a){const t=this.is3DSEnabled&&d?yield this.get3DS(a.bigpayToken,(null==a?void 0:a.iin)||""):void 0;return{methodId:e,paymentData:{deviceSessionId:s,formattedPayload:{paypal_fastlane_token:{token:t||a.bigpayToken}}}}}const{getPaymentToken:l}=this.getBraintreeCardComponentOrThrow(),c=yield l({name:{fullName:o},billingAddress:this.mapToPayPalAddress(r)}),u=(null===(i=null===(t=c.paymentSource.card)||void 0===t?void 0:t.binDetails)||void 0===i?void 0:i.bin)||"",h=this.is3DSEnabled&&d?yield this.get3DS(c.id,u):void 0;return{methodId:e,paymentData:{deviceSessionId:s,nonce:h||c.id}}})}get3DS(e,t){return xe(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=yield this.braintreeSdk.getBraintreeThreeDS(),r=i.getOrderOrThrow();return new Promise((i,o)=>{n.verifyCard({amount:null==r?void 0:r.orderAmount,nonce:e,bin:t,onLookupComplete:(e,t)=>{n.on("customer-canceled",()=>{"function"==typeof this.onError&&this.onError(new Q),o(new Q)}),t()}},(e,t)=>(e&&"THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT"===e.code&&("function"==typeof this.onError&&this.onError(new Q),o(new Q)),i(t.nonce)))})})}mapToPayPalAddress(e){return{streetAddress:(null==e?void 0:e.address1)||"",locality:(null==e?void 0:e.city)||"",region:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCodeAlpha2:(null==e?void 0:e.countryCode)||""}}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getCustomerOrThrow(),n=e.getPaymentProviderCustomer(),r=_e(n)?n:{},o=this.braintreeFastlaneUtils.getSessionIdFromCookies();return!(!i.isGuest||(null==r?void 0:r.authenticationState)===O.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}getBraintreeCardComponentOrThrow(){if(!this.braintreeCardComponent)throw new g;return this.braintreeCardComponent}getPayPalInstruments(){const e=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow();return(_e(e)?e:{}).instruments||[]}handleBraintreeStoredInstrumentChange(e){return xe(this,void 0,void 0,function*(){const t=this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow(),{selectionChanged:i,selectedCard:n}=yield t.profile.showCardSelector();if(i){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),i=_e(t)?t:{},r=this.braintreeFastlaneUtils.mapPayPalToBcInstrument(e,[n]);if(r&&r.length>0)return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},i),{instruments:[...r]})),r[0]}})}}!function(e){e.CVV="cvv",e.PAN="pan"}(Be||(Be={}));class Le{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,i=document.cookie;let n=null;const r=i.indexOf(t);if(r>-1){let e=i.indexOf(";",r);-1===e&&(e=i.length),n=decodeURIComponent(i.substring(r+t.length,e))}return n}static set(e,t,i={secure:!0}){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:r,path:o,domain:a,secure:s}=i;if(r)n+=`; expires=${r.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),n+=`; expires=${e.toUTCString()}`}o&&(n+=`; path=${o}`),a&&(n+=`; domain=${a}`),s&&(n+="; secure"),document.cookie=n}static remove(e,t){Le.set(e,"",Object.assign({expires:new Date(0)},t))}}var Ve=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class je{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}getDeviceSessionId(){return Ve(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getCart();return this.braintreeIntegrationService.getSessionId(null==e?void 0:e.id)})}initializeBraintreeFastlaneOrThrow(e,t){return Ve(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getCart(),{clientToken:r,config:o}=i.getPaymentMethodOrThrow(e);if(!r)throw new U(j.MissingPaymentMethod);this.methodId=e,this.braintreeIntegrationService.initialize(r),this.braintreeFastlane=yield this.braintreeIntegrationService.getBraintreeFastlane(null==n?void 0:n.id,o.testMode,t)})}getBraintreeFastlaneOrThrow(){if(!this.braintreeFastlane)throw new g;return this.braintreeFastlane}getBraintreeFastlaneComponentOrThrow(){return this.getBraintreeFastlaneOrThrow().FastlaneCardComponent}runPayPalAuthenticationFlowOrThrow(e,t){var i;return Ve(this,void 0,void 0,function*(){try{const n=this.getMethodIdOrThrow(),r=this.getBraintreeFastlaneOrThrow(),{lookupCustomerByEmail:o,triggerAuthenticationFlow:a}=r.identity,s=this.paymentIntegrationService.getState(),d=s.getCartOrThrow(),l=s.getCustomer(),c=s.getBillingAddress(),{isFastlaneShippingOptionAutoSelectEnabled:u}=s.getPaymentMethodOrThrow(n).initializationData||{},h=e||(null==l?void 0:l.email)||(null==c?void 0:c.email)||"",{customerContextId:y}=yield o(h);if(!y)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:O.UNRECOGNIZED,addresses:[],instruments:[]}),void this.saveSessionIdToCookies(d.id);const{authenticationState:m,profileData:p}=yield a(y),g=(null===(i=null==p?void 0:p.shippingAddress)||void 0===i?void 0:i.phoneNumber)||"";if(m===O.CANCELED)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:[],instruments:[]}),void this.removeSessionIdFromCookies();const v=this.mapPayPalToBcAddress([p.shippingAddress],[g])||[],f=this.getPayPalBillingAddresses(p),b=f?this.mapPayPalToBcAddress([f],[g]):[],w=p.card?this.mapPayPalToBcInstrument(n,[p.card]):[],C=this.mergeShippingAndBillingAddresses(v,b);if(this.saveSessionIdToCookies(d.id),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:C,instruments:w}),b.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateBillingAddress(b[0])),b.length>0&&d.lineItems.digitalItems.length>0&&0===d.lineItems.physicalItems.length){const{firstName:e,lastName:t}=C[0],i=Object.assign(Object.assign({},b[0]),{firstName:e,lastName:t});yield this.paymentIntegrationService.updateBillingAddress(i)}v.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateShippingAddress(v[0]),t&&u&&(yield this.setShippingOption()))}catch(e){}})}getSessionIdFromCookies(){return Le.get("bc-fastlane-sessionId")||""}saveSessionIdToCookies(e){const t=new Date;t.setDate(t.getDate()+14),Le.set("bc-fastlane-sessionId",e,{expires:t,secure:!0})}removeSessionIdFromCookies(){Le.remove("bc-fastlane-sessionId")}mapPayPalToBcInstrument(e,t){if(t)return t.map(t=>{const{id:i,paymentSource:n}=t,{brand:r,expiry:o,lastDigits:a,binDetails:s}=n.card,[d,l]=o.split("-");return{bigpayToken:i,brand:r,defaultInstrument:!1,expiryMonth:l,expiryYear:d,iin:(null==s?void 0:s.bin)||"",last4:a,method:e,provider:e,trustedShippingAddress:!1,type:"card",untrustedShippingCardVerificationMode:Be.PAN}})}mapPayPalToBcAddress(e,t){if(!e)return[];const i=this.paymentIntegrationService.getState().getCountries()||[],n=e=>{const t=i.find(t=>t.code===e);return(null==t?void 0:t.name)||""};return e.map(e=>({id:Date.now(),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:n(e.countryCodeAlpha2),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:t&&t[0]||"",customFields:[]}))}getPayPalBillingAddresses(e){const{card:t,name:i}=e||{};if(!t)return;const{firstName:r,lastName:o}=t.paymentSource.card.billingAddress,{firstName:a,lastName:s}=i||{},{shippingAddress:d}=e||{},l=Object.assign(Object.assign({},t.paymentSource.card.billingAddress),{firstName:r||a,lastName:o||s});return d&&n(this.normalizeAddress(l),this.normalizeAddress(d))?d:l}normalizeAddress(e){return a(e,["id"])}mergeShippingAndBillingAddresses(e,t){const i=t.filter(t=>!e.some(e=>n(this.normalizeAddress(e),this.normalizeAddress(t))));return[...e,...i]}getMethodIdOrThrow(){if(!this.methodId)throw new V('Unable to proceed because "methodId" argument is not provided.');return this.methodId}setShippingOption(){var e;return Ve(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getConsignments()||[],i=(null===(e=t[0])||void 0===e?void 0:e.availableShippingOptions)||[],n=i.find(e=>e.isRecommended);if(n||i.length){const e=n||i[0];yield this.paymentIntegrationService.selectShippingOption(e.id)}})}}const Ue=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i),o=new je(t,r),a=new z(e(),i,n),s=new B(a);return new Fe(t,o,s)},[{id:"braintreeacceleratedcheckout"}]);var Re=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class He{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i}initialize(e){return Re(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:i}=e;if(!t)throw new V('Unable to initialize payment because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState();this.paymentMethod=n.getPaymentMethodOrThrow(i);const r=n.getCheckoutOrThrow(),a=n.getStoreConfigOrThrow(),{clientToken:s,config:d}=this.paymentMethod||{};if(!s)throw new U(j.MissingPaymentMethod);const{onError:l=o,onPaymentSelect:c=o}=t;this.braintreeSdk.initialize(s);const u=yield this.braintreeSdk.getBraintreeVisaCheckout(),h=yield this.braintreeSdk.getVisaCheckoutSdk(null==d?void 0:d.testMode),y=u.createInitOptions({settings:{locale:a.storeProfile.storeLanguage,shipping:{collectShipping:!1}},paymentRequest:{currencyCode:a.currency.code,subtotal:String(r.subtotal)}});yield h.init(y),h.on("payment.success",e=>this.tokenizePayment(u,e).then(()=>Promise.all([this.paymentIntegrationService.loadCheckout(),this.paymentIntegrationService.loadPaymentMethod(i)])).then(()=>c()).catch(e=>l(e))),h.on("payment.error",(e,t)=>l(t))})}execute(e,t){var i,n;return Re(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!r)throw new V('Unable to submit payment because "payload.payment" argument is not provided.');if(!(null===(n=null===(i=this.paymentMethod)||void 0===i?void 0:i.initializationData)||void 0===n?void 0:n.nonce))throw new U(j.MissingPaymentMethod);const{nonce:a}=this.paymentMethod.initializationData;try{yield this.paymentIntegrationService.submitOrder(o,t),yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},r),{paymentData:{nonce:a}}))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new W)}deinitialize(){return Re(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}tokenizePayment(e,t){return Re(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(n),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}handleError(e){if(e instanceof Error&&"BraintreeError"===e.name)throw new $(e.message);throw e}}const We=L(t=>{const i=window,n=new F(t),r=new B(new z(e(),i,n));return new He(t,u(),r)},[{id:"braintreevisacheckout"}]);var qe=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class $e{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}initialize(e){return qe(this,void 0,void 0,function*(){const{methodId:t}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState();this.venmoOptions=e.braintreevenmo;const n=i.getPaymentMethodOrThrow(t);yield this.initializeBraintreeVenmo(n)})}execute(e){return qe(this,void 0,void 0,function*(){const{payment:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!t)throw new R(["payment"]);try{const e=yield this.preparePaymentData(t);yield this.paymentIntegrationService.submitOrder(i),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new W)}deinitialize(){return qe(this,void 0,void 0,function*(){return yield this.braintreeIntegrationService.teardown(),Promise.resolve()})}handleError(e){if(!D(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Q(e.message);throw new $(e.message)}initializeBraintreeVenmo(e){var t;return qe(this,void 0,void 0,function*(){const{clientToken:i}=e;if(!i)throw new U(j.MissingPaymentMethod);const n=x(this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features,"PAYPAL-5406.braintree_venmo_web_fallback_support");try{this.braintreeIntegrationService.initialize(i),this.braintreeVenmoCheckout=yield this.braintreeIntegrationService.getVenmoCheckout(Object.assign(Object.assign({},void 0!==(null===(t=this.venmoOptions)||void 0===t?void 0:t.allowDesktop)?{allowDesktop:this.venmoOptions.allowDesktop}:{}),n?{mobileWebFallBack:n}:{}))}catch(e){this.handleError(e)}})}preparePaymentData(e){return qe(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{nonce:i}=t.getPaymentMethodOrThrow(e.methodId);if(i)return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(i)});const n=yield this.braintreeVenmoTokenize(),r=yield this.braintreeIntegrationService.getSessionId();return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(n.nonce,n.details.email,r)})})}formattedPayload(e,t,i){return{formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:i||null,paypal_account:{token:e,email:t||null}}}}braintreeVenmoTokenize(){return new Promise((e,t)=>{var i;null===(i=this.braintreeVenmoCheckout)||void 0===i||i.tokenize((i,n)=>{if(i)return t(i);e(n)})})}}const Ge=L(t=>{const i=window,n=e(),r=new F(t),o=new z(n,i,r),a=new le(o,i);return new $e(t,a)},[{id:"braintreevenmo"}]);var Ye=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Je{constructor(e,t,i){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeHostedForm=i}initialize(e){return Ye(this,void 0,void 0,function*(){const{methodId:t,gatewayId:i,braintree:n}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState();this.paymentMethod=r.getPaymentMethodOrThrow(t);const{clientToken:o}=this.paymentMethod;if(!o)throw new U(j.MissingPaymentMethod);this.threeDSecure=null==n?void 0:n.threeDSecure,this.onPaymentError=null==n?void 0:n.onPaymentError;try{this.braintreeIntegrationService.initialize(o,this.threeDSecure),this.isHostedPaymentFormEnabled(t,i)&&(null==n?void 0:n.form)&&(yield this.braintreeHostedForm.initialize(n.form,n.unsupportedCardBrands,o),this.isHostedFormInitialized=this.braintreeHostedForm.isInitialized()),this.is3dsEnabled=this.paymentMethod.config.is3dsEnabled,this.deviceSessionId=yield this.braintreeIntegrationService.getSessionId(),this.shouldInitializeBraintreeFastlane()&&(yield this.initializeBraintreeFastlaneOrThrow(t))}catch(e){return this.handleError(e,t)}})}execute(e){return Ye(this,void 0,void 0,function*(){const{payment:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!t)throw new R(["payment"]);this.isHostedFormInitialized&&this.braintreeHostedForm.validate(),yield this.paymentIntegrationService.submitOrder(i);const n=this.paymentIntegrationService.getState(),r=n.getBillingAddressOrThrow(),o=n.getOrderOrThrow().orderAmount;try{const e=this.isHostedFormInitialized?yield this.prepareHostedPaymentData(t,r,o):yield this.preparePaymentData(t,r,o);yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},t),{paymentData:e}))}catch(e){return this.processAdditionalAction(e,t,o)}})}finalize(){return Promise.reject(new W)}deinitialize(){return Ye(this,void 0,void 0,function*(){return this.isHostedFormInitialized=!1,yield Promise.all([this.braintreeIntegrationService.teardown(),this.braintreeHostedForm.deinitialize()]),Promise.resolve()})}handleError(e,t){var i;if(ge(e)){if(!(t&&this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:t})||"HOSTED_FIELDS_INVALID_FIELD_SELECTOR"!==e.code))return;if(e.code.startsWith("THREEDS_"))return null===(i=this.onPaymentError)||void 0===i||i.call(this,new $("THREEDS_VERIFICATION_FAILED")),Promise.reject();throw new $(e.message)}throw e}preparePaymentData(e,t,i){return Ye(this,void 0,void 0,function*(){const{paymentData:n}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e))return Object.assign(Object.assign({},r),n);const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=q(n)?n:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.braintreeIntegrationService.verifyCard(e,t,i):yield this.braintreeIntegrationService.tokenizeCard(e,t);return Object.assign(Object.assign({},r),{nonce:s,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})})}prepareHostedPaymentData(e,t,i){return Ye(this,void 0,void 0,function*(){const{paymentData:n}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e)){const{nonce:e}=yield this.braintreeHostedForm.tokenizeForStoredCardVerification();return Object.assign(Object.assign(Object.assign({},r),n),{nonce:e})}const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=q(n)?n:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.verifyCardWithHostedForm(t,i):yield this.braintreeHostedForm.tokenize(t);return Object.assign(Object.assign({},r),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,nonce:s})})}verifyCardWithHostedForm(e,t){return Ye(this,void 0,void 0,function*(){const i=yield this.braintreeHostedForm.tokenize(e);return this.braintreeIntegrationService.challenge3DSVerification(i,t)})}processAdditionalAction(e,t,i){return Ye(this,void 0,void 0,function*(){if(!(e=>"object"==typeof e&&null!==e&&"body"in e)(e)||!d(e.body.errors,{code:"three_d_secure_required"}))return this.handleError(e);try{const{payer_auth_request:n}=function(e){return"object"==typeof e&&null!==e&&"name"in e&&"body"in e&&"status"in e.body&&"three_ds_result"in e.body&&"payer_auth_request"in e.body.three_ds_result&&"errors"in e.body}(e)&&e.body.three_ds_result||{},{paymentData:r}=t,o=this.paymentIntegrationService.getState();if(!r||!H(r))throw new R(["instrumentId"]);const a=o.getCardInstrumentOrThrow(r.instrumentId),{nonce:s}=yield this.braintreeIntegrationService.challenge3DSVerification({nonce:n||"",bin:a.iin},i);yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},t),{paymentData:{deviceSessionId:this.deviceSessionId,nonce:s}}))}catch(e){return this.handleError(e)}})}isHostedPaymentFormEnabled(e,t){return!!e&&!0===this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled}isSubmittingWithStoredCard(e){return!(!e.paymentData||!H(e.paymentData))}shouldPerform3DSVerification(e){return!(!this.is3dsEnabled||this.isSubmittingWithStoredCard(e))}shouldInitializeBraintreeFastlane(){var e;const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),i=_e(t)?t:{};return(null===(e=this.paymentMethod)||void 0===e?void 0:e.initializationData.isAcceleratedCheckoutEnabled)&&!(null==i?void 0:i.authenticationState)}initializeBraintreeFastlaneOrThrow(e){return Ye(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getPaymentMethodOrThrow(e),{clientToken:r,config:o}=n;if(!r)throw new U(j.MissingPaymentMethod);this.braintreeIntegrationService.initialize(r,this.threeDSecure),yield this.braintreeIntegrationService.getBraintreeFastlane(i.id,o.testMode)})}}function Ke(e){return"cardNumber"in e}function Xe(e){if(!D(e))return!1;const{details:t}=e;return void 0===t||"object"==typeof t&&null!==t&&void 0===t.invalidFieldKeys||(i=t,Array.isArray(i)&&i.every(e=>"string"==typeof e));var i}var Qe,Ze=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e[e.CreditCard=0]="CreditCard",e[e.StoredCardVerification=1]="StoredCardVerification"}(Qe||(Qe={}));class et{constructor(e,t){this.braintreeScriptLoader=e,this.braintreeSDKVersionManager=t,this.isInitializedHostedForm=!1,this.handleBlur=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onBlur)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy),errors:this.mapErrors(e.fields)})},this.handleFocus=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onFocus)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleCardTypeChange=e=>{var t,i;const n=1===e.cards.length?e.cards[0].type.replace(/^master-card$/,"mastercard"):void 0;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onCardTypeChange)||void 0===i||i.call(t,{cardType:n})},this.handleInputSubmitRequest=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onEnter)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleValidityChange=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===i||i.call(t,{isValid:this.isValidForm(e),errors:this.mapValidationErrors(e.fields)})}}initialize(e,t,n){var r,o,a,s,d;return Ze(this,void 0,void 0,function*(){this.clientToken=n,this.formOptions=e,this.type=Ke(e.fields)?Qe.CreditCard:Qe.StoredCardVerification;const l=this.mapFieldOptions(e.fields,t);i(l)?this.isInitializedHostedForm=!1:(this.cardFields=yield this.createHostedFields({fields:l,styles:e.styles&&this.mapStyleOptions(e.styles)}),null===(r=this.cardFields)||void 0===r||r.on("blur",this.handleBlur),null===(o=this.cardFields)||void 0===o||o.on("focus",this.handleFocus),null===(a=this.cardFields)||void 0===a||a.on("cardTypeChange",this.handleCardTypeChange),null===(s=this.cardFields)||void 0===s||s.on("validityChange",this.handleValidityChange),null===(d=this.cardFields)||void 0===d||d.on("inputSubmitRequest",this.handleInputSubmitRequest),this.isInitializedHostedForm=!0)})}isInitialized(){return!!this.isInitializedHostedForm}deinitialize(){var e;return Ze(this,void 0,void 0,function*(){this.isInitializedHostedForm&&(this.isInitializedHostedForm=!1,yield null===(e=this.cardFields)||void 0===e?void 0:e.teardown())})}validate(){if(!this.cardFields)throw new M(C.PaymentNotInitialized);const e=this.cardFields.getState();if(!this.isValidForm(e)){this.handleValidityChange(e);const t=this.mapValidationErrors(e.fields);throw new X(t)}}tokenize(e){var t,i,n,o,a;return Ze(this,void 0,void 0,function*(){if(!this.cardFields)throw new M(C.PaymentNotInitialized);try{const o=yield this.cardFields.tokenize(s({billingAddress:e&&this.mapBillingAddress(e)},r));return null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===i||i.call(t,{isValid:!0,errors:{}}),{nonce:o.nonce,bin:null===(n=o.details)||void 0===n?void 0:n.bin}}catch(e){if(Xe(e)){const t=this.mapTokenizeError(e);if(t)throw null===(a=null===(o=this.formOptions)||void 0===o?void 0:o.onValidate)||void 0===a||a.call(o,{isValid:!1,errors:t}),new X(t)}throw e}})}tokenizeForStoredCardVerification(){var e,t,i,n,r;return Ze(this,void 0,void 0,function*(){if(!this.cardFields)throw new M(C.PaymentNotInitialized);try{const n=yield this.cardFields.tokenize();return null===(t=null===(e=this.formOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,{isValid:!0,errors:{}}),{nonce:n.nonce,bin:null===(i=n.details)||void 0===i?void 0:i.bin}}catch(e){if(Xe(e)){const t=this.mapTokenizeError(e,!0);if(t)throw null===(r=null===(n=this.formOptions)||void 0===n?void 0:n.onValidate)||void 0===r||r.call(n,{isValid:!1,errors:t}),new X(t)}throw e}})}createHostedFields(e){return Ze(this,void 0,void 0,function*(){const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadHostedFields(),n=this.braintreeSDKVersionManager.getSDKVersion()===v?Object.assign(Object.assign({},e),{preventCursorJumps:!0}):e;return i.create(Object.assign(Object.assign({},n),{client:t}))})}getClient(){return Ze(this,void 0,void 0,function*(){if(!this.clientToken)throw new M(C.PaymentNotInitialized);if(!this.client){const e=yield this.braintreeScriptLoader.loadClient();this.client=e.create({authorization:this.clientToken})}return this.client})}mapBillingAddress(e){return{countryName:e.country,postalCode:e.postalCode,streetAddress:e.address2?`${e.address1} ${e.address2}`:e.address1}}mapFieldOptions(e,t){if(Ke(e)){const i={};return null==t||t.forEach(e=>{(e=>Object.values(T).includes(e))(e)&&(i[e]=!1)}),s({number:Object.assign({container:`#${e.cardNumber.containerId}`,placeholder:e.cardNumber.placeholder,internalLabel:e.cardNumber.accessibilityLabel},Object.keys(i).length>0?{supportedCardBrands:i}:{}),expirationDate:{container:`#${e.cardExpiry.containerId}`,placeholder:e.cardExpiry.placeholder,internalLabel:e.cardExpiry.accessibilityLabel},cvv:e.cardCode&&{container:`#${e.cardCode.containerId}`,placeholder:e.cardCode.placeholder,internalLabel:e.cardCode.accessibilityLabel},cardholderName:{container:`#${e.cardName.containerId}`,placeholder:e.cardName.placeholder,internalLabel:e.cardName.accessibilityLabel}},r)}return s({number:e.cardNumberVerification&&{container:`#${e.cardNumberVerification.containerId}`,placeholder:e.cardNumberVerification.placeholder},cvv:e.cardCodeVerification&&{container:`#${e.cardCodeVerification.containerId}`,placeholder:e.cardCodeVerification.placeholder}},r)}mapStyleOptions(e){const t=(e={})=>s({color:e.color,"font-family":e.fontFamily,"font-size":e.fontSize,"font-weight":e.fontWeight},r);return{input:t(e.default),".invalid":t(e.error),":focus":t(e.focus)}}mapFieldType(e){switch(e){case"number":return this.type===Qe.StoredCardVerification?m.CardNumberVerification:m.CardNumber;case"expirationDate":return m.CardExpiry;case"cvv":return this.type===Qe.StoredCardVerification?m.CardCodeVerification:m.CardCode;case"cardholderName":return m.CardName;default:throw new Error("Unexpected field type")}}mapErrors(e){const t={};if(e)for(const[i,n]of Object.entries(e))if(n&&this.isValidParam(i)){const{isValid:e,isEmpty:r,isPotentiallyValid:o}=n;t[i]={isValid:e,isEmpty:r,isPotentiallyValid:o}}return t}mapValidationErrors(e){return Object.keys(e).reduce((t,i)=>{var n;return Object.assign(Object.assign({},t),{[this.mapFieldType(i)]:(null===(n=e[i])||void 0===n?void 0:n.isValid)?void 0:[this.createInvalidError(this.mapFieldType(i))]})},{})}mapTokenizeError(e,t=!1){var i,n;if("HOSTED_FIELDS_FIELDS_EMPTY"===e.code){const e=[this.createRequiredError(this.mapFieldType("cvv"))];return t?{[this.mapFieldType("cvv")]:e}:{[this.mapFieldType("cvv")]:e,[this.mapFieldType("expirationDate")]:[this.createRequiredError(this.mapFieldType("expirationDate"))],[this.mapFieldType("number")]:[this.createRequiredError(this.mapFieldType("number"))],[this.mapFieldType("cardholderName")]:[this.createRequiredError(this.mapFieldType("cardholderName"))]}}return null===(n=null===(i=e.details)||void 0===i?void 0:i.invalidFieldKeys)||void 0===n?void 0:n.reduce((e,t)=>{const i=this.mapFieldType(t);return Object.assign(Object.assign({},e),{[i]:[this.createInvalidError(i)]})},{})}createRequiredError(e){var t;return{fieldType:e,message:null!==(t={[m.CardCode]:"CVV is required",[m.CardCodeVerification]:"CVV is required",[m.CardNumber]:"Credit card number is required",[m.CardNumberVerification]:"Credit card number is required",[m.CardExpiry]:"Expiration date is required",[m.CardName]:"Full name is required"}[e])&&void 0!==t?t:"Field is required",type:"required"}}createInvalidError(e){var t,i,n,r;const o={[m.CardCode]:{message:"Invalid card code",type:"invalid_card_code"},[m.CardCodeVerification]:{message:"Invalid card code",type:"invalid_card_code"},[m.CardNumber]:{message:"Invalid card number",type:"invalid_card_number"},[m.CardNumberVerification]:{message:"Invalid card number",type:"invalid_card_number"},[m.CardExpiry]:{message:"Invalid card expiry",type:"invalid_card_expiry"},[m.CardName]:{message:"Invalid card name",type:"invalid_card_name"}};return{fieldType:e,message:null!==(i=null===(t=o[e])||void 0===t?void 0:t.message)&&void 0!==i?i:"Invalid field",type:null!==(r=null===(n=o[e])||void 0===n?void 0:n.type)&&void 0!==r?r:"invalid"}}isValidForm(e){return Object.keys(e.fields).every(t=>{var i;return null===(i=e.fields[t])||void 0===i?void 0:i.isValid})}isValidParam(e){return["number","cvv","expirationDate","postalCode","cardholderName","cardType"].includes(e)}}const tt=L(t=>{const i=window,n=new F(t),r=new z(e(),i,n),o=new le(r,i),a=new et(r,n);return new Je(t,o,a)},[{id:"braintree"}]);var it=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class nt{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return it(this,void 0,void 0,function*(){const{braintreepaypal:t,methodId:i}=e,{container:n,onError:r}=t||{};if(!i)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new V('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!n)throw new V('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(i),!o.clientToken)throw new U(j.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(i),o=a.getPaymentMethodOrThrow(i)}const{clientToken:s,config:d,initializationData:l}=o,{paymentButtonStyles:c}=l||{},{checkoutTopButtonStyles:u}=c||{};if(!s||!l)throw new U(j.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:l.intent,isCreditEnabled:l.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,i,Boolean(d.testMode),u)},e=>this.handleError(e,n,r))})}deinitialize(){return it(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return it(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return it(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,i,n,r){const{container:a,onClick:s=o}=t,{paypal:d}=this.braintreeHostWindow,l=null==d?void 0:d.FUNDING.PAYPAL;if(d&&l){const o=d.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(n),fundingSource:l,style:Object.assign(Object.assign({},r),{height:40}),createOrder:()=>this.setupPayment(e,t,i),onApprove:n=>this.tokenizePayment(n,e,i,t),onClick:s});o.isEligible()&&o.render(`#${a}`)}else this.braintreeIntegrationService.removeElement(a)}setupPayment(e,t,i){var n;return it(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(i),d=null==a?void 0:a.addresses[0],l=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:l,amount:r,currency:o,offerCredit:!1,intent:null===(n=s.initializationData)||void 0===n?void 0:n.intent})}catch(e){const{container:i,onError:n}=t;this.handleError(e,i,n)}})}tokenizePayment(e,t,i,n){return it(this,void 0,void 0,function*(){try{const{deviceData:n}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:i,action:"set_external_checkout",nonce:a,device_data:n,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:i}=n;this.handleError(e,t,i)}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!D(e))throw e;i(e)}}const rt=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i);return new nt(t,u(),r,i)},[{id:"braintreepaypal"}]);var ot=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class at{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return ot(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,methodId:i}=e,{container:n,onError:r}=t||{};if(!i)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new V('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!n)throw new V('Unable to initialize payment because "options.braintreepaypalcredit.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(i),!o.clientToken)throw new U(j.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(i),o=a.getPaymentMethodOrThrow(i)}const{clientToken:s,config:d,initializationData:l}=o,{paymentButtonStyles:c}=l||{},{checkoutTopButtonStyles:u}=c||{};if(!s||!l)throw new U(j.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:l.intent,isCreditEnabled:l.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,i,Boolean(d.testMode),Object.assign(Object.assign({},u),{height:40}))},e=>this.handleError(e,n,r))})}deinitialize(){return ot(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return ot(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return ot(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,i,n,r){const{container:a,onClick:s=o}=t,{paypal:d}=this.braintreeHostWindow;let l=!1;d&&[d.FUNDING.PAYLATER,d.FUNDING.CREDIT].forEach(o=>{if(!l){const c=d.Buttons({env:n?"sandbox":"production",fundingSource:o,style:r,createOrder:()=>this.setupPayment(e,t,i),onApprove:n=>this.tokenizePayment(n,e,i,t),onClick:s});c.isEligible()&&(c.render(`#${a}`),l=!0)}}),d&&l||this.braintreeIntegrationService.removeElement(a)}setupPayment(e,t,i){var n;return ot(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(i),d=null==a?void 0:a.addresses[0],l=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:l,amount:r,currency:o,offerCredit:!0,intent:null===(n=s.initializationData)||void 0===n?void 0:n.intent})}catch(e){const{container:i,onError:n}=t;this.handleError(e,i,n)}})}tokenizePayment(e,t,i,n){return ot(this,void 0,void 0,function*(){try{const{deviceData:n}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:i,action:"set_external_checkout",nonce:a,device_data:n,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:i}=n;this.handleError(e,t,i)}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!D(e))throw e;i(e)}}const st=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i);return new at(t,u(),r,i)},[{id:"braintreepaypalcredit"}]);var dt=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class lt{constructor(e,t){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.isAcceleratedCheckoutEnabled=!1}initialize({methodId:e,braintreefastlane:t}){var i;return dt(this,void 0,void 0,function*(){if(!e)throw new V('Unable to proceed because "methodId" argument is not provided.');const n=yield this.getValidPaymentMethodOrThrow(e),{isAcceleratedCheckoutEnabled:r,isFastlaneStylingEnabled:o}=n.initializationData||{},a=o?null===(i=n.initializationData)||void 0===i?void 0:i.fastlaneStyles:void 0;this.isAcceleratedCheckoutEnabled=!!r;try{if(this.isAcceleratedCheckoutEnabled){const e=De(a,null==t?void 0:t.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(n.id,e)}}catch(e){}return Promise.resolve()})}deinitialize(){return dt(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return dt(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return dt(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return dt(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:i}=e||{};if("function"!=typeof i)throw new V('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');const n=this.paymentIntegrationService.getState().getCustomerOrThrow();if(this.isAcceleratedCheckoutEnabled&&n.isGuest){const e=yield this.shouldRunAuthenticationFlow();t&&"function"==typeof t&&t(),e&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(void 0,!0))}i()})}shouldRunAuthenticationFlow(){var e;return dt(this,void 0,void 0,function*(){const t="braintreeacceleratedcheckout";try{yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t);return(null===(e=i.initializationData)||void 0===e?void 0:e.shouldRunAcceleratedCheckout)||!1}catch(e){return!1}})}getValidPaymentMethodOrThrow(e){return dt(this,void 0,void 0,function*(){let t=e;try{yield this.paymentIntegrationService.loadPaymentMethod(t)}catch(i){t="braintree"===e?"braintreeacceleratedcheckout":"braintree",yield this.paymentIntegrationService.loadPaymentMethod(t)}return this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)})}}const ct=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i),o=new je(t,r);return new lt(t,o)},[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);class ut extends p{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var ht=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class yt{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i,this.buttonClassName="visa-checkout-wrapper",this.onError=o}initialize(e){return ht(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:i}=e;if(!i)throw new V('Unable to proceed because "methodId" argument is not provided.');if(!t)throw new V('Unable to proceed because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState(),r=n.getCheckoutOrThrow(),{clientToken:a,config:s}=n.getPaymentMethodOrThrow(i),d=n.getStoreConfigOrThrow();if(!a)throw new U(j.MissingPaymentMethod);this.braintreeSdk.initialize(a);const l=yield this.braintreeSdk.getBraintreeVisaCheckout(),c=yield this.braintreeSdk.getVisaCheckoutSdk(s.testMode),{container:u,onError:h}=t;this.onError=h||o;const y=l.createInitOptions({paymentRequest:{currencyCode:d.currency.code,subtotal:String(r.subtotal)},settings:{locale:d.storeProfile.storeLanguage,shipping:{collectShipping:!0}}}),m=this.createSignInButton(u,this.buttonClassName);yield c.init(y),c.on("payment.success",e=>this.tokenizePayment(l,e).then(()=>this.paymentIntegrationService.loadCheckout()).catch(e=>this.handleError(e))),c.on("payment.error",(e,t)=>this.handleError(t)),m.style.visibility="visible"})}deinitialize(){return ht(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}signIn(){throw new ut('In order to sign in via VisaCheckout, the shopper must click on "Visa Checkout" button.')}signOut(e){return ht(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}tokenizePayment(e,t){return ht(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(n),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e,t){const i=document.querySelector(`#${e}`);if(!i)throw new Error("Unable to proceed because the provided container ID is not valid.");return this.insertVisaCheckoutButton(i,t)}insertVisaCheckoutButton(e,t){const i=document.createElement("div");return i.style.display="flex",i.style.flexDirection="column",i.style.visibility="hidden",i.style.width="max-content",i.className=t,i.innerHTML='\n <img\n alt="Visa Checkout"\n class="v-button"\n role="button"\n src="https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178"\n />\n <a class="v-learn v-learn-default" style="text-align: right; display: block; font-size: 10px; color: #003366;" href="#" data-locale="en_US">Tell Me More</a>',e.appendChild(i),i}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const mt=L(t=>{const i=window,n=new F(t),r=new B(new z(e(),i,n));return new yt(t,u(),r)},[{id:"braintreevisacheckout"}]);class pt extends p{constructor(e){super(e||"An unexpected error has occurred during buy now cart creation process. Please try again later."),this.name="BuyNowCartCreationError",this.type="buy_now_cart_creation_error"}}function gt(e){const{color:t,fundingicons:i,height:n=40,layout:o,shape:a,size:d,tagline:l}=e||{},c={color:t,fundingicons:i,height:vt(n),layout:o,shape:a||"rect",size:d,tagline:l};return s(c,r)}function vt(e){const t=Number(e);return!t||Number.isNaN(t)?40:t>55?55:t<25?25:t}var ft=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class bt{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return ft(this,void 0,void 0,function*(){const{braintreepaypal:t,containerId:i,methodId:n}=e;if(!n)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new V('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new V('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new V('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(n),{clientToken:s,config:d,initializationData:l}=a;if(!s||!l)throw new U(j.MissingPaymentMethod);const c={currency:r,intent:l.intent,isCreditEnabled:l.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(c,e=>{this.renderPayPalButton(e,t,i,n,!!d.testMode)},e=>this.handleError(e,i,t.onError))})}deinitialize(){return ft(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,i,n,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:l}=this.braintreeHostWindow;if(l){const c=l.Buttons({env:r?"sandbox":"production",fundingSource:l.FUNDING.PAYPAL,style:gt(o),createOrder:()=>this.setupPayment(e,t,n),onApprove:t=>this.tokenizePayment(t,e,n,a,s)});c.isEligible()?c.render(`#${i}`):d&&"function"==typeof d&&d()}else this.braintreeIntegrationService.removeElement(i)}setupPayment(e,t,i){var n;return ft(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),l=s.getPaymentMethodOrThrow(i),c=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),y=h?ve(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:y,amount:c,currency:u,offerCredit:!1,intent:null===(n=l.initializationData)||void 0===n?void 0:n.intent})}catch(e){throw r&&(D(e)||e instanceof p)&&r(e),e}})}tokenizePayment(e,t,i,n,r){return ft(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),l=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:i,action:n?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(l)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(D(e)||e instanceof p)&&r(e),e}})}createBuyNowCart(e){return ft(this,void 0,void 0,function*(){if(!e)throw new U(j.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new pt}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!D(e))throw e;i(e)}}const wt=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i);return new bt(t,u(),r,i)},[{id:"braintreepaypal"}]);var Ct=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class St{constructor(e,t,i,n,r){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeMessages=n,this.braintreeHostWindow=r}initialize(e){var t,i;return Ct(this,void 0,void 0,function*(){const{braintreepaypalcredit:n,containerId:r,methodId:o}=e;if(!o)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new V('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new V('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');let a,s=this.paymentIntegrationService.getState();if(n.buyNowInitializeOptions){if(!n.currencyCode)throw new V('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');a=n.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),s=this.paymentIntegrationService.getState(),a=s.getCartOrThrow().currency.code;const d=s.getPaymentMethodOrThrow(o),{clientToken:l,config:c,initializationData:u}=d;if(!l||!u)throw new U(j.MissingPaymentMethod);const h={currency:a,intent:u.intent,isCreditEnabled:u.isCreditEnabled,commit:!1},y=x(null!==(i=null===(t=s.getStoreConfig())||void 0===t?void 0:t.checkoutSettings.features)&&void 0!==i?i:{},"PAYPAL-5663.hide_braintree_card_banner_implementation_in_checkout_sdk");this.braintreeIntegrationService.initialize(l),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{!y&&n.messagingContainerId&&this.renderPayPalMessages(o,n.messagingContainerId),this.renderPayPalButton(e,n,r,o,!!c.testMode)},e=>this.handleError(e,r,n.onError))})}deinitialize(){return Ct(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,se.CART)}renderPayPalButton(e,t,i,n,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:l}=this.braintreeHostWindow;let c=!1;l&&[l.FUNDING.PAYLATER,l.FUNDING.CREDIT].forEach(u=>{const h=u===l.FUNDING.CREDIT?Object.assign({label:oe.CREDIT},gt(o)):gt(o);if(!c){const o=l.Buttons({env:r?"sandbox":"production",fundingSource:u,style:h,createOrder:()=>this.setupPayment(e,t,n),onApprove:t=>this.tokenizePayment(t,e,n,a,s)});o.isEligible()?(o.render(`#${i}`),c=!0):l.FUNDING.CREDIT&&d&&"function"==typeof d&&d()}}),l&&c||this.braintreeIntegrationService.removeElement(i)}setupPayment(e,t,i){var n;return Ct(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),l=s.getPaymentMethodOrThrow(i),c=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),y=h?ve(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:y,amount:c,currency:u,offerCredit:!0,intent:null===(n=l.initializationData)||void 0===n?void 0:n.intent})}catch(e){throw r&&(D(e)||e instanceof p)&&r(e),e}})}tokenizePayment(e,t,i,n,r){return Ct(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),l=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:i,action:n?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(l)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(D(e)||e instanceof p)&&r(e),e}})}createBuyNowCart(e){return Ct(this,void 0,void 0,function*(){if(!e)throw new U(j.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new pt}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!D(e))throw e;i(e)}}const Pt=L(t=>{const i=window,n=new F(t),r=new le(new z(e(),i,n),i),o=new ce(t);return new St(t,u(),r,o,i)},[{id:"braintreepaypalcredit"}]);var It=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ot{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i}initialize(e){return It(this,void 0,void 0,function*(){const{containerId:t,methodId:i}=e;if(!i)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new V('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState(),{clientToken:r,initializationData:o,config:a}=n.getPaymentMethodOrThrow(i);if(!r||!o)throw new U(j.MissingPaymentMethod);this.braintreeSdk.initialize(r);const s=yield this.braintreeSdk.getBraintreeVisaCheckout(),{currency:{code:d},cartAmount:l}=n.getCartOrThrow(),c=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),u=s.createInitOptions({paymentRequest:{currencyCode:d,subtotal:String(l)},settings:{shipping:{collectShipping:!0}}});this.createSignInButton(t),yield c.init(u),c.on("payment.success",e=>It(this,void 0,void 0,function*(){yield this.paymentSuccess(s,e)}))})}deinitialize(){return Promise.resolve()}paymentSuccess(e,t){return It(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.toVisaCheckoutAddress(n),billingAddress:a=this.toVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}toVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e){const t=document.querySelector(`#${e}`);if(!t)throw new Error("Need a container to place the button");return this.insertVisaCheckoutButton(t)}insertVisaCheckoutButton(e){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="flex-end",t.innerHTML='\n <img\n alt="Visa Checkout"\n class="v-button"\n role="button"\n src="https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178"\n />\n <a class="v-learn v-learn-default" style="text-align: right; display: block; font-size: 10px; color: #003366;" href="#" data-locale="en_US">Tell Me More</a>',e.appendChild(t),t}}const kt=L(t=>{const i=window,n=new F(t),r=new B(new z(e(),i,n));return new Ot(t,u(),r)},[{id:"braintreevisacheckout"}]);function Et(e){const{billingAddress:t,email:i,firstName:n,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:i,first_name:n,last_name:r,phone_number:o,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}function Tt(e){const{email:t,phone:i,shippingAddress:n}=e,r=(null==n?void 0:n.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:i,address_line_1:null==n?void 0:n.line1,address_line_2:null==n?void 0:n.line2,city:null==n?void 0:n.city,state:null==n?void 0:n.state,country_code:null==n?void 0:n.countryCode,postal_code:null==n?void 0:n.postalCode}}var At=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};const zt=e=>{const{color:t,height:i}=e;return{backgroundColor:(n=t||"",n===re.WHITE?"#FFFFFF":"#3D95CE"),backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:`url("/app/assets/img/payment-providers/venmo-logo-${t===re.WHITE?re.BLUE:re.WHITE}.svg")`,backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:`${i||40}px`,minWidth:"150px",height:"100%",width:"100%",border:t===re.WHITE?"1px solid black":"none"};var n};class Nt{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i,this.onError=o}initialize(e){return At(this,void 0,void 0,function*(){const{braintreevenmo:t,containerId:i,methodId:n}=e;if(!n)throw new V('Unable to initialize payment because "options.methodId" argument is not provided.');const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{clientToken:o,initializationData:a}=r,{paymentButtonStyles:s}=a,{cartButtonStyles:d}=s||{},l=(null==t?void 0:t.style)||d;if(!o||!a)throw new U(j.MissingPaymentMethod);if(!i)throw new V('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadDefaultCheckout(),this.onError=(null==t?void 0:t.onError)||this.handleError,this.braintreeSdk.initialize(o);try{const e=yield this.braintreeSdk.getVenmoCheckoutOrThrow();this.renderVenmoButton(e,i,null==t?void 0:t.buyNowInitializeOptions,l)}catch(e){(ge(e)||function(e){return e instanceof N}(e))&&this.handleInitializationVenmoError(e,i)}})}deinitialize(){return At(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}handleError(e){throw new Error(e.message)}createBuyNowCart(e){return At(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=null==e?void 0:e.getBuyNowCartRequestBody();if(!t)throw new U(j.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new pt}}})}handleInitializationVenmoError(e,t){return this.removeVenmoContainer(t),this.onError(e)}removeVenmoContainer(e){const t=document.getElementById(e);t&&t.remove()}renderVenmoButton(e,t,i,n){const r=document.getElementById(t),{color:o}=n||{};if(!r)throw new V("Unable to create wallet button without valid container ID.");r.setAttribute("aria-label","Venmo"),Object.assign(r.style,zt(n||{})),r.addEventListener("click",()=>At(this,void 0,void 0,function*(){r.setAttribute("disabled","true");const t=yield this.createBuyNowCart(i);e.tokenize&&e.tokenize((e,i)=>At(this,void 0,void 0,function*(){r.removeAttribute("disabled"),e&&this.onError(e),yield this.handlePostForm(i,null==t?void 0:t.id)}))})),o===re.BLUE&&(r.addEventListener("mouseenter",()=>{r.style.backgroundColor="#0a7fc2"}),r.addEventListener("mouseleave",()=>{r.style.backgroundColor=zt(n||{}).backgroundColor}))}handlePostForm(e,t){return At(this,void 0,void 0,function*(){const{deviceData:i}=yield this.braintreeSdk.getDataCollectorOrThrow(),{nonce:n,details:r}=e;this.formPoster.postForm("/checkout.php",Object.assign({nonce:n,provider:"braintreevenmo",payment_type:"paypal",device_data:i,action:"set_external_checkout",billing_address:JSON.stringify(Et(r)),shipping_address:JSON.stringify(Tt(r))},t&&{cart_id:t}))})}}const Mt=L(t=>{const i=window,n=e(),r=new F(t),o=new z(n,i,r),a=new B(o);return new Nt(t,u(),a)},[{id:"braintreevenmo"}]);export{K as createBraintreeAchPaymentStrategy,tt as createBraintreeCreditCardPaymentStrategy,ct as createBraintreeFastlaneCustomerStrategy,Ue as createBraintreeFastlanePaymentStrategy,Ne as createBraintreeLocalMethodsPaymentStrategy,wt as createBraintreePaypalButtonStrategy,Pt as createBraintreePaypalCreditButtonStrategy,st as createBraintreePaypalCreditCustomerStrategy,rt as createBraintreePaypalCustomerStrategy,we as createBraintreePaypalPaymentStrategy,Mt as createBraintreeVenmoButtonStrategy,Ge as createBraintreeVenmoPaymentStrategy,kt as createBraintreeVisaCheckoutButtonStrategy,mt as createBraintreeVisaCheckoutCustomerStrategy,We as createBraintreeVisaCheckoutPaymentStrategy};
2
2
  //# sourceMappingURL=braintree.js.map