@bigcommerce/checkout-sdk 1.904.1 → 1.904.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/checkout-button.js +1 -1
- package/dist/cjs/checkout-sdk-essential.js +1 -1
- package/dist/cjs/checkout-sdk.js +1 -1
- package/dist/cjs/hosted-form-v2-iframe-host.js +1 -1
- package/dist/cjs/integrations/amazon-pay.js +1 -1
- package/dist/cjs/integrations/bigcommerce-payments.js +1 -1
- package/dist/cjs/integrations/braintree.js +1 -1
- package/dist/cjs/integrations/google-pay.js +1 -1
- package/dist/cjs/integrations/klarna.js +1 -1
- package/dist/cjs/integrations/paypal-commerce.js +1 -1
- package/dist/cjs/integrations/paypal-express.js +1 -1
- package/dist/cjs/integrations/zip.js +1 -1
- package/dist/esm/checkout-button.js +1 -1
- package/dist/esm/checkout-sdk-essential.js +1 -1
- package/dist/esm/checkout-sdk.js +1 -1
- package/dist/esm/hosted-form-v2-iframe-host.js +1 -1
- package/dist/esm/integrations/amazon-pay.js +1 -1
- package/dist/esm/integrations/bigcommerce-payments.js +1 -1
- package/dist/esm/integrations/braintree.js +1 -1
- package/dist/esm/integrations/google-pay.js +1 -1
- package/dist/esm/integrations/klarna.js +1 -1
- package/dist/esm/integrations/paypal-commerce.js +1 -1
- package/dist/esm/integrations/paypal-express.js +1 -1
- package/dist/esm/integrations/zip.js +1 -1
- package/dist/types/checkout-sdk.d.ts +1 -1
- package/dist/types/internal-mappers.d.ts +1 -1
- package/docs/interfaces/ShippingOption.md +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{createRequestSender as n,createTimeout as i}from"@bigcommerce/request-sender";import{ScriptLoader as r,createScriptLoader as o,getScriptLoader as a,getStylesheetLoader as s}from"@bigcommerce/script-loader";import{combineReducers as d,composeReducers as c,createAction as l,createDataStore as u,createErrorAction as h,deepFreeze as p}from"@bigcommerce/data-store";import{Observable as m,Subject as y,concat as g,defer as f,empty as v,from as _,fromEvent as S,merge as I,noop as w,of as C,throwError as b}from"rxjs";import{catchError as P,delay as O,distinctUntilChanged as E,filter as A,map as T,retryWhen as k,shareReplay as D,switchMap as M,take as z}from"rxjs/operators";import{cond as x,constant as N,difference as R,each as F,filter as L,find as j,findIndex as B,flatMap as U,flatten as q,get as V,identity as G,includes as H,isArray as W,isEmpty as $,isEqual as Y,isMatch as K,isNil as J,isObject as Z,isPlainObject as Q,isString as X,isUndefined as ee,kebabCase as te,keyBy as ne,keys as ie,last as re,map as oe,max as ae,memoize as se,merge as de,noop as ce,omit as le,omitBy as ue,overSome as he,pick as pe,pickBy as me,reduce as ye,round as ge,some as fe,stubTrue as ve,transform as _e,union as Se,uniq as Ie,uniqueId as we,values as Ce,without as be}from"lodash";import{memoize as Pe,memoizeOne as Oe}from"@bigcommerce/memoize";import{createFormPoster as Ee}from"@bigcommerce/form-poster";import{supportsPopups as Ae}from"@braintree/browser-detection";import{default as Te}from"local-storage-fallback";import{createClient as ke}from"@bigcommerce/bigpay-client";import{creditCardType as De,number as Me}from"card-validator";import{exclude as ze,parseUrl as xe,stringifyUrl as Ne}from"query-string";import{createSelector as Re,createSelectorCreator as Fe,defaultMemoize as Le}from"reselect";import{default as je}from"shallowequal";import{IntlMessageFormat as Be}from"intl-messageformat";var Ue={785:t=>{t.exports=e},939:e=>{e.exports=t}},qe={};function Ve(e){var t=qe[e];if(void 0!==t)return t.exports;var n=qe[e]={exports:{}};return Ue[e](n,n.exports,Ve),n.exports}Ve.d=(e,t)=>{for(var n in t)Ve.o(t,n)&&!Ve.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},Ve.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ve.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var Ge={};Ve.r(Ge),Ve.d(Ge,{createAmazonPayV2CustomerStrategy:()=>wi,createApplePayCustomerStrategy:()=>Xi,createBigCommercePaymentsCustomerStrategy:()=>br,createBigCommercePaymentsFastlaneCustomerStrategy:()=>Hr,createBigCommercePaymentsPayLaterCustomerStrategy:()=>Yr,createBigCommercePaymentsVenmoCustomerStrategy:()=>Zr,createBoltCustomerStrategy:()=>so,createBraintreeFastlaneCustomerStrategy:()=>zo,createBraintreePaypalCreditCustomerStrategy:()=>Oo,createBraintreePaypalCustomerStrategy:()=>Co,createBraintreeVisaCheckoutCustomerStrategy:()=>Ro,createGooglePayAdyenV2CustomerStrategy:()=>ca,createGooglePayAdyenV3CustomerStrategy:()=>la,createGooglePayAuthorizeDotNetCustomerStrategy:()=>ha,createGooglePayBigCommercePaymentsCustomerStrategy:()=>as,createGooglePayBnzCustomerStrategy:()=>Sa,createGooglePayBraintreeCustomerStrategy:()=>Ya,createGooglePayCheckoutComCustomerStrategy:()=>fa,createGooglePayCybersourceCustomerStrategy:()=>_a,createGooglePayOrbitalCustomerStrategy:()=>wa,createGooglePayPayPalCommerceCustomerStrategy:()=>is,createGooglePayStripeCustomerStrategy:()=>qa,createGooglePayStripeUpeCustomerStrategy:()=>Va,createGooglePayTdOnlineMartCustomerStrategy:()=>ls,createGooglePayWorldpayAccessCustomerStrategy:()=>Ha,createPayPalCommerceCreditCustomerStrategy:()=>Js,createPayPalCommerceCustomerStrategy:()=>zs,createPayPalCommerceFastlaneCustomerStrategy:()=>sd,createPayPalCommerceVenmoCustomerStrategy:()=>Xs,createStripeLinkV2CustomerStrategy:()=>wd,createStripeUPECustomerStrategy:()=>ud});var He={};Ve.r(He),Ve.d(He,{createAdyenV2PaymentStrategy:()=>Ld,createAdyenV3PaymentStrategy:()=>Vd,createAffirmPaymentStrategy:()=>Yd,createAfterpayPaymentStrategy:()=>tc,createAmazonPayV2PaymentStrategy:()=>rc,createApplePayPaymentStrategy:()=>dc,createBigCommercePaymentsAlternativeMethodsPaymentStrategy:()=>Nc,createBigCommercePaymentsCreditCardsPaymentStrategy:()=>Mc,createBigCommercePaymentsFastlanePaymentStrategy:()=>vc,createBigCommercePaymentsPayLaterPaymentStrategy:()=>Ic,createBigCommercePaymentsPaymentStrategy:()=>mc,createBigCommercePaymentsRatePayPayPaymentStrategy:()=>Pc,createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy:()=>Fc,createBigCommercePaymentsVenmoPaymentStrategy:()=>Bc,createBlueSnapDirectAPMPaymentStrategy:()=>al,createBlueSnapDirectCreditCardPaymentStrategy:()=>rl,createBlueSnapV2PaymentStrategy:()=>ul,createBoltPaymentStrategy:()=>vl,createBraintreeAchPaymentStrategy:()=>wl,createBraintreeCreditCardPaymentStrategy:()=>Ql,createBraintreeFastlanePaymentStrategy:()=>Ll,createBraintreeLocalMethodsPaymentStrategy:()=>xl,createBraintreePaypalPaymentStrategy:()=>kl,createBraintreeVenmoPaymentStrategy:()=>Gl,createBraintreeVisaCheckoutPaymentStrategy:()=>Ul,createCBAMPGSPaymentStrategy:()=>ou,createCheckoutComAPMPaymentStrategy:()=>Iu,createCheckoutComCreditCardPaymentStrategy:()=>mu,createCheckoutComFawryPaymentStrategy:()=>cu,createCheckoutComIdealPaymentStrategy:()=>vu,createCheckoutComSepaPaymentStrategy:()=>gu,createClearpayPaymentStrategy:()=>Pu,createCreditCardPaymentStrategy:()=>Ou,createCyberSourcePaymentStrategy:()=>Uu,createCyberSourceV2PaymentStrategy:()=>Wu,createGooglePayAdyenV2PaymentStrategy:()=>Qu,createGooglePayAdyenV3PaymentStrategy:()=>th,createGooglePayAuthorizeNetPaymentStrategy:()=>nh,createGooglePayBigCommercePaymentsPaymentStrategy:()=>vh,createGooglePayBraintreePaymentStrategy:()=>dh,createGooglePayCheckoutComPaymentStrategy:()=>ih,createGooglePayCybersourcePaymentStrategy:()=>rh,createGooglePayOrbitalPaymentStrategy:()=>oh,createGooglePayPPCPPaymentStrategy:()=>ph,createGooglePayStripePaymentStrategy:()=>ah,createGooglePayTdOnlineMartPaymentStrategy:()=>_h,createGooglePayWorldpayAccessPaymentStrategy:()=>sh,createHummPaymentStrategy:()=>wh,createKlarnaPaymentStrategy:()=>Ah,createKlarnaV2PaymentStrategy:()=>zh,createLegacyPaymentStrategy:()=>Nh,createMolliePaymentStrategy:()=>Uh,createMonerisPaymentStrategy:()=>Hh,createNoPaymentStrategy:()=>Pd,createOfflinePaymentStrategy:()=>$h,createOffsitePaymentStrategy:()=>Jh,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>lp,createPayPalCommerceCreditCardsPaymentStrategy:()=>pp,createPayPalCommerceCreditPaymentStrategy:()=>ip,createPayPalCommerceFastlanePaymentStrategy:()=>Sp,createPayPalCommercePaymentStrategy:()=>ep,createPayPalCommerceRatePayPaymentStrategy:()=>gp,createPayPalCommerceVenmoPaymentStrategy:()=>ap,createPayPalProPaymentStrategy:()=>zp,createPaypalExpressPaymentStrategy:()=>kp,createSagePayPaymentStrategy:()=>Np,createSezzlePaymentStrategy:()=>Lp,createSquareV2PaymentStrategy:()=>Wp,createStripeCSPaymentStrategy:()=>ym,createStripeOCSPaymentStrategy:()=>hm,createStripeUPEPaymentStrategy:()=>dm,createStripeV3PaymentStrategy:()=>im,createTDOnlineMartPaymentStrategy:()=>Sm,createWorldpayAccessOpenBankingPaymentStrategy:()=>Em,createWorldpayAccessPaymentStrategy:()=>Pm,createZipPaymentStrategy:()=>km});const We="b2bExtraField_";function $e(e){return e.name.startsWith(We)}function Ye(e){var t;const{fieldType:n,type:i}=function(e){switch(e){case"multiline_text":return{fieldType:"multiline",type:"string"};case"number":return{fieldType:"text",type:"integer"};case"dropdown":return{fieldType:"dropdown",type:"array"};default:return{fieldType:"text",type:"string"}}}(e.type);let r;return e.config.numberOfRows&&(r={rows:e.config.numberOfRows}),(null===(t=e.config.options)||void 0===t?void 0:t.length)&&(r=Object.assign(Object.assign({},r),{items:e.config.options.map(e=>({value:e,label:e}))})),{id:`${We}${e.id}`,name:`${We}${e.id}`,custom:!1,label:e.name,hidden:!e.visibleToStorefront,required:e.isRequired,default:null!=e.config.defaultValue?String(e.config.defaultValue):void 0,fieldType:n,type:i,maxLength:e.config.maxLength,max:e.config.maxValue,options:r}}function Ke(e,t,n){return(i=t)&&i.type&&i.error?g(C(t),b(h(e,t.payload,n))):b(h(e,t,n));var i}var Je;!function(e){e.LoadB2BTokenRequested="LOAD_B2B_TOKEN_REQUESTED",e.LoadB2BTokenSucceeded="LOAD_B2B_TOKEN_SUCCEEDED",e.LoadB2BTokenFailed="LOAD_B2B_TOKEN_FAILED"}(Je||(Je={}));const Ze="",Qe="";class Xe{constructor(e){this._requestSender=e}loadB2BToken(e){return t=>{var n;const i=t.getState(),{storeHash:r}=i.config.getStoreConfigOrThrow().storeProfile,{b2bBaseUrl:o=Ze,b2bClientId:a=Qe}=null!==(n=i.config.getStoreConfigOrThrow().checkoutSettings.b2bServiceDetails)&&void 0!==n?n:{},{id:s}=i.customer.getCustomerOrThrow(),{channelId:d}=i.checkout.getCheckoutOrThrow();return g(C(l(Je.LoadB2BTokenRequested)),f(()=>{return t=this,n=void 0,c=function*(){const{body:t}=yield this._requestSender.getB2BToken(a,s,r,d,o,e);return l(Je.LoadB2BTokenSucceeded,{token:t.data.token})},new((i=void 0)||(i=Promise))(function(e,r){function o(e){try{s(c.next(e))}catch(e){r(e)}}function a(e){try{s(c.throw(e))}catch(e){r(e)}}function s(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(o,a)}s((c=c.apply(t,n||[])).next())});var t,n,i,c})).pipe(P(e=>Ke(Je.LoadB2BTokenFailed,e)))}}}const et={"X-Checkout-SDK-Version":"1.904.1"};var tt,nt;class it{constructor(e){this._requestSender=e}getB2BToken(e,t,n,i,r,o){return a=this,s=void 0,c=function*(){const{body:a}=yield this._requestSender.get("/customer/current.jwt",{timeout:null==o?void 0:o.timeout,params:{app_client_id:e},headers:et});return this._requestSender.post(`${r}/api/v2/login`,{timeout:null==o?void 0:o.timeout,credentials:!1,headers:{"Content-Type":"application/json"},body:{bcToken:a.token,customerId:t,storeHash:n,channelId:i}})},new((d=void 0)||(d=Promise))(function(e,t){function n(e){try{r(c.next(e))}catch(e){t(e)}}function i(e){try{r(c.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof d?r:new d(function(e){e(r)})).then(n,i)}r((c=c.apply(a,s||[])).next())});var a,s,d,c}}class rt 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}}!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.MissingPaymentProviderCustomer=13]="MissingPaymentProviderCustomer",e[e.MissingPaymentRedirectUrl=14]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=15]="MissingPaymentStatus",e[e.MissingPaymentToken=16]="MissingPaymentToken",e[e.MissingShippingAddress=17]="MissingShippingAddress"}(tt||(tt={}));class ot extends rt{constructor(e){super(function(e){switch(e){case tt.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case tt.MissingCart:return"Unable to proceed because cart data is unavailable.";case tt.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case tt.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case tt.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case tt.MissingCheckoutConfig:case tt.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case tt.MissingOrder:return"Unable to proceed because order data is unavailable.";case tt.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case tt.MissingPayment:return"Unable to proceed because payment data is unavailable.";case tt.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case tt.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case tt.MissingPaymentProviderCustomer:return"Unable to proceed because payment provider customer is unavailable.";case tt.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"}}!function(e){e.UpdateBillingAddressRequested="UPDATE_BILLING_ADDRESS_REQUESTED",e.UpdateBillingAddressSucceeded="UPDATE_BILLING_ADDRESS_SUCCEEDED",e.UpdateBillingAddressFailed="UPDATE_BILLING_ADDRESS_FAILED",e.ContinueAsGuestRequested="CONTINUE_AS_GUEST_REQUESTED",e.ContinueAsGuestSucceeded="CONTINUE_AS_GUEST_SUCCEEDED",e.ContinueAsGuestFailed="CONTINUE_AS_GUEST_FAILED"}(nt||(nt={}));class at extends rt{constructor(e){super(e||"Unable to continue as a guest because the customer is already signed in."),this.name="UnableToContinueAsGuestError",this.type="unable_to_continue_as_guest"}}var st;class dt{constructor(e,t){this._requestSender=e,this._subscriptionActionCreator=t}continueAsGuest(e,t){return n=>{const i=n.getState(),r=i.checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);const o=i.customer.getCustomer();if(o&&!o.isGuest)throw new at;const a=i.billingAddress.getBillingAddress();let s;if(a){const{country:t}=a,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(a,["country"]);s=Object.assign(Object.assign({},n),e)}else s=e;const d=!$(a);return I(g(C(l(nt.ContinueAsGuestRequested)),f(()=>{return e=this,n=void 0,o=function*(){const{body:e}=yield this._createOrUpdateBillingAddress(r.id,s,d,t);return l(nt.ContinueAsGuestSucceeded,e)},new((i=void 0)||(i=Promise))(function(t,r){function a(e){try{d(o.next(e))}catch(e){r(e)}}function s(e){try{d(o.throw(e))}catch(e){r(e)}}function d(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((o=o.apply(e,n||[])).next())});var e,n,i,o})).pipe(P(e=>Ke(nt.ContinueAsGuestFailed,e))),this._updateCustomerConsent(e,t))}}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout();if(!o)throw new ot(tt.MissingCheckout);i.next(l(nt.UpdateBillingAddressRequested));const a=r.billingAddress.getBillingAddress(),s=!$(a),d=Object.assign(Object.assign({},e),{email:void 0===e.email&&a?a.email:e.email});a&&a.id&&(d.id=a.id),this._createOrUpdateBillingAddress(o.id,d,s,t).then(({body:e})=>{i.next(l(nt.UpdateBillingAddressSucceeded,e)),i.complete()}).catch(e=>{i.error(h(nt.UpdateBillingAddressFailed,e))})})}_updateCustomerConsent({email:e,acceptsAbandonedCartEmails:t,acceptsMarketingNewsletter:n},i){return null==t&&null==n?v():this._subscriptionActionCreator.updateSubscriptions({email:e,acceptsMarketingNewsletter:n||!1,acceptsAbandonedCartEmails:t||!1},i)}_createOrUpdateBillingAddress(e,t,n,i){return n?this._requestSender.updateAddress(e,t,i):this._requestSender.createAddress(e,t,i)}}class ct extends rt{constructor(e){super(e||"Your checkout could not be processed because your cart is empty. Please add items to your cart and try again."),this.name="EmptyCartError",this.type="empty_cart"}}!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(st||(st={}));const lt=st;const ut={include:["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"].join(",")};class ht{constructor(e){this._requestSender=e}createAddress(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/billing-address`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(i,{body:t,params:ut,headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}updateAddress(e,t,{timeout:n}={}){const{id:i}=t,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["id"]),o=`/api/storefront/checkouts/${e}/billing-address/${i}`,a=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.put(o,{params:ut,body:r,headers:a,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}var pt,mt;function yt(e,t){const n=u((e,t)=>t.type===pt.Synchronize?t.payload:e,e.getState(),{stateTransformer:t});return e.subscribe(e=>{n.dispatch(l(pt.Synchronize,e))},{initial:!1}),n}!function(e){e.Synchronize="SYNCHRONIZE"}(pt||(pt={})),function(e){e.ClearError="CLEAR_ERROR"}(mt||(mt={}));class gt{clearError(e){return{type:mt.ClearError,payload:e}}}class ft{constructor(e,t){this._requestSender=e,this._config=t}sendRequest(e,t){return this._requestSender.sendRequest(e,t)}get(e,t){return this._requestSender.get(e,t)}post(e,t){return this._requestSender.post(this._prefixed(e),t)}put(e,t){return this._requestSender.put(this._prefixed(e),t)}patch(e,t){return this._requestSender.patch(this._prefixed(e),t)}delete(e,t){return this._requestSender.delete(this._prefixed(e),t)}_prefixed(e){const t=this._config.getBasePath();return!this._config.getFeatures()["CHECKOUT-9950.update_sf_checkout_url_for_subfolder"]||!t||t.endsWith("/checkout")||/^https?:\/\//.test(e)?e:`${t}${e}`}}function vt(){try{return"production"}catch(e){return"development"}}class _t{constructor(e){this._console=e}log(...e){this._logToConsole("log",...e)}info(...e){this._logToConsole("info",...e)}warn(...e){this._logToConsole("warn",...e)}error(...e){this._logToConsole("error",...e)}debug(...e){this._logToConsole("debug",...e)}_logToConsole(e,...t){this._console&&this._console[e]&&this._console[e].call(this._console,...t)}}class St{log(){}info(){}warn(){}error(){}debug(){}}const It=function(e=!0){return e?new _t(console):new St}("test"!==vt());function wt(){return It}function Ct(e,t,n){const i=new WeakMap;function r(e){return(...n)=>{const r=n[n.length-1],{useCache:o}=(a=r)&&"boolean"==typeof a.useCache?r:{useCache:!1};var a;if(!o)return e.call(this,...n);const s=i.get(this)||{};var d;return i.get(this)||i.set(this,s),s[t]||(s[t]=(d=e,Pe(function(...e){const t=d.call(this,...e);return t instanceof m?_(t).pipe(D()):"function"==typeof t?Pe(e=>_(t(e)).pipe(D()),{isEqual:Y}):t},{isEqual:Y}))),s[t].call(this,...n)}}return{get(){if("function"!=typeof n.value)throw new Error("Decorator should be used in functions");const e=r.call(this,n.value);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e}}}var bt;!function(e){e.LoadConfigRequested="LOAD_CONFIG_REQUESTED",e.LoadConfigSucceeded="LOAD_CONFIG_SUCCEEDED",e.LoadConfigFailed="LOAD_CONFIG_FAILED"}(bt||(bt={}));class Pt{constructor(e){this._configRequestSender=e}loadConfig(e){return m.create(t=>{t.next(l(bt.LoadConfigRequested)),this._configRequestSender.loadConfig(e).then(e=>{t.next(l(bt.LoadConfigSucceeded,e.body)),t.complete()}).catch(e=>{t.error(h(bt.LoadConfigFailed,e))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Ct],Pt.prototype,"loadConfig",null);const Ot={body:{},headers:{},status:0};class Et extends rt{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||Ot;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}class At extends Et{constructor(e){super(e,{message:e.body.title}),this.name="CheckoutNotAvailableError",this.type="checkout_not_available"}}const Tt="This API endpoint is for internal use only and may change in the future";class kt{constructor(e){this._requestSender=e}loadConfig({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-settings",{timeout:e,headers:Object.assign({Accept:lt.JsonV1,"X-API-INTERNAL":Tt},et),params:t}).catch(e=>{if(e.status>=400&&e.status<500)throw new At(e);throw e})}}var Dt;!function(e){e.ApplyCouponRequested="APPLY_COUPON_REQUESTED",e.ApplyCouponSucceeded="APPLY_COUPON_SUCCEEDED",e.ApplyCouponFailed="APPLY_COUPON_FAILED",e.RemoveCouponRequested="REMOVE_COUPON_REQUESTED",e.RemoveCouponSucceeded="REMOVE_COUPON_SUCCEEDED",e.RemoveCouponFailed="REMOVE_COUPON_FAILED"}(Dt||(Dt={}));class Mt{constructor(e){this._couponRequestSender=e}applyCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);i.next(l(Dt.ApplyCouponRequested)),this._couponRequestSender.applyCoupon(r.id,e,t).then(({body:e})=>{i.next(l(Dt.ApplyCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Dt.ApplyCouponFailed,e))})})}removeCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);i.next(l(Dt.RemoveCouponRequested)),this._couponRequestSender.removeCoupon(r.id,e,t).then(({body:e})=>{i.next(l(Dt.RemoveCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Dt.RemoveCouponFailed,e))})})}}const zt=["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","customer.customerGroup","payments","promotions.banners"];var xt,Nt,Rt,Ft;function Lt(e){return Ie(e).join(",")}!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(xt||(xt={}));class jt{constructor(e){this._requestSender=e}applyCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Lt([...zt,xt.AvailableShippingOptions])},body:{couponCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}removeCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons/${t}`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Lt([...zt,xt.AvailableShippingOptions])}}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}!function(e){e.ApplyGiftCertificateRequested="APPLY_GIFT_CERTIFICATE_REQUESTED",e.ApplyGiftCertificateSucceeded="APPLY_GIFT_CERTIFICATE_SUCCEEDED",e.ApplyGiftCertificateFailed="APPLY_GIFT_CERTIFICATE_FAILED",e.RemoveGiftCertificateRequested="REMOVE_GIFT_CERTIFICATE_REQUESTED",e.RemoveGiftCertificateSucceeded="REMOVE_GIFT_CERTIFICATE_SUCCEEDED",e.RemoveGiftCertificateFailed="REMOVE_GIFT_CERTIFICATE_FAILED"}(Nt||(Nt={}));class Bt{constructor(e){this._giftCertificateRequestSender=e}applyGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);i.next(l(Nt.ApplyGiftCertificateRequested)),this._giftCertificateRequestSender.applyGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.ApplyGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.ApplyGiftCertificateFailed,e))})})}removeGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);i.next(l(Nt.RemoveGiftCertificateRequested)),this._giftCertificateRequestSender.removeGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.RemoveGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.RemoveGiftCertificateFailed,e))})})}}class Ut{constructor(e){this._requestSender=e}applyGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Lt(zt)},body:{giftCertificateCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}removeGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates/${t}`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Lt(zt)}}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}function qt(e){return e&&"resolveIds"in e}class Vt extends rt{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Gt{constructor(e){var t,n,i;this._factories={},this._instances={},this._defaultToken=null!==(t=null==e?void 0:e.defaultToken)&&void 0!==t?t:"default",this._useFallback=null===(n=null==e?void 0:e.useFallback)||void 0===n||n,this._tokenResolver=null!==(i=null==e?void 0:e.tokenResolver)&&void 0!==i?i:e=>e}get(e,t){try{return this._getInstance(e||this._defaultToken,t||e||this._defaultToken)}catch(e){if(!this._useFallback)throw e;return this._getInstance(this._defaultToken,t||this._defaultToken)}}getFactory(e,t){const n=this._tokenResolver(e,Object.keys(this._factories),t);return n?this._factories[n]:void 0}register(e,t){if(this._hasFactory(e))throw new Vt(`'${e}' is already registered.`);this._factories[e]=t}_hasFactory(e){return!!this._factories[e]}_hasInstance(e){return!!this._instances[e]}_getInstance(e,t){if(!this._hasInstance(t)){const n=this.getFactory(e);if(!n)throw new Vt(`'${e}' is not registered.`);this._instances[t]=n()}return this._instances[t]}}class Ht{constructor(e=!1){this._useFallback=e,this._registry=new Gt({tokenResolver:this._resolveToken.bind(this),defaultToken:this._encodeToken({default:!0}),useFallback:this._useFallback})}get(e){return this._registry.get(this._encodeToken(e))}getFactory(e,t){try{return this._registry.getFactory(this._encodeToken(e),t)}catch(e){return}}getUseFallback(){return this._useFallback}register(e,t){this._registry.register(this._encodeToken(e),t)}_encodeToken(e){return btoa(JSON.stringify(e))}_decodeToken(e){return JSON.parse(atob(e))}_resolveToken(e,t,n){var i;const r=this._decodeToken(e),o=[];t.forEach(e=>{const t=this._decodeToken(e),n={token:e,matches:0,default:!1,totalKeys:Object.keys(t).length};for(const[e,i]of Object.entries(t)){if(e in r&&r[e]!==i){n.matches=0;break}e in r&&r[e]===i&&n.matches++,"default"===e&&!0===i&&(n.default=!0)}o.push(n)});const a=o.sort((e,t)=>t.matches-e.matches).filter(e=>e.matches>0);a.length>1&&a[0].matches===a[1].matches&&"development"===vt()&&wt().warn("The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.");const s=Object.keys(r).length;if(n){const e=a.find(e=>e.matches===s&&e.matches===e.totalKeys);if(!e)throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)} with exact match.`);return e.token}const d=a[0];if(d&&d.token)return d.token;if(this._useFallback){const e=null===(i=o.find(e=>e.default))||void 0===i?void 0:i.token;if(e)return e}throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)}.`)}}function Wt(e){const t=e;return"object"==typeof t&&"object"==typeof t.payload&&"string"==typeof t.payload.token}!function(e){e.BuyNow="BUY_NOW"}(Rt||(Rt={})),function(e){e.SignInCustomerRequested="SIGN_IN_CUSTOMER_REQUESTED",e.SignInCustomerSucceeded="SIGN_IN_CUSTOMER_SUCCEEDED",e.SignInCustomerFailed="SIGN_IN_CUSTOMER_FAILED",e.SignOutCustomerRequested="SIGN_OUT_CUSTOMER_REQUESTED",e.SignOutCustomerSucceeded="SIGN_OUT_CUSTOMER_SUCCEEDED",e.SignOutCustomerFailed="SIGN_OUT_CUSTOMER_FAILED",e.CreateCustomerRequested="CREATE_CUSTOMER_REQUESTED",e.CreateCustomerSucceeded="CREATE_CUSTOMER_SUCCEEDED",e.CreateCustomerFailed="CREATE_CUSTOMER_FAILED",e.CreateCustomerAddressRequested="CREATE_CUSTOMER_ADDRESS_REQUESTED",e.CreateCustomerAddressSucceeded="CREATE_CUSTOMER_ADDRESS_SUCCEEDED",e.CreateCustomerAddressFailed="CREATE_CUSTOMER_ADDRESS_FAILED",e.StripeLinkAuthenticated="STRIPE_LINK_AUTHENTICATED"}(Ft||(Ft={}));var $t,Yt,Kt;class Jt{constructor(e,t,n){this._customerRequestSender=e,this._checkoutActionCreator=t,this._spamProtectionActionCreator=n}createCustomer(e,t){return n=>{const i=n.getState().config.getStoreConfigOrThrow(),{isStorefrontSpamProtectionEnabled:r}=i.checkoutSettings,o=i=>_(this._customerRequestSender.createAccount(Object.assign(Object.assign({},e),{token:i}),t)).pipe(M(()=>g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Ft.CreateCustomerSucceeded)))));return g(C(l(Ft.CreateCustomerRequested)),r?_(this._spamProtectionActionCreator.execute()(n)).pipe(M(e=>{var t;return Wt(e)?g(C(e),o(null===(t=e.payload)||void 0===t?void 0:t.token)):C(e)})):o()).pipe(P(e=>Ke(Ft.CreateCustomerFailed,e)))}}createAddress(e,t){return g(C(l(Ft.CreateCustomerAddressRequested)),f(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._customerRequestSender.createAddress(e,t);return l(Ft.CreateCustomerAddressSucceeded,n)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Ke(Ft.CreateCustomerAddressFailed,e)))}signInCustomer(e,t){return n=>{const i=n.getState().checkout.getCheckoutOrThrow(),r=i.cart.source===Rt.BuyNow?i.id:void 0;return g(C(l(Ft.SignInCustomerRequested)),_(this._customerRequestSender.signInCustomer(Object.assign(Object.assign({},e),{cartId:r}),t)).pipe(M(({body:e})=>e.data.persistentCartRetrievalInformation?g(this._checkoutActionCreator.loadCheckout(e.data.persistentCartRetrievalInformation.id,t)(n),C(l(Ft.SignInCustomerSucceeded,e.data))):g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Ft.SignInCustomerSucceeded,e.data)))))).pipe(P(e=>Ke(Ft.SignInCustomerFailed,e)))}}signOutCustomer(e){return t=>{const n=t.getState().checkout.getCheckoutOrThrow(),i=n.cart.source===Rt.BuyNow?n.id:void 0;return g(C(l(Ft.SignOutCustomerRequested)),_(this._customerRequestSender.signOutCustomer(e,i)).pipe(M(({body:n})=>g(this._checkoutActionCreator.loadCurrentCheckout(e)(t),C(l(Ft.SignOutCustomerSucceeded,n.data)))))).pipe(P(e=>Ke(Ft.SignOutCustomerFailed,e)))}}}class Zt{constructor(e){this._requestSender=e}createAccount(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer",{timeout:t,headers:et,body:e})}createAddress(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer-address",{timeout:t,headers:et,body:e})}signInCustomer(e,{timeout:t}={}){return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:t,headers:et,body:e})}signOutCustomer({timeout:e}={},t){return this._requestSender.delete("/internalapi/v1/checkout/customer",Object.assign({timeout:e,headers:et},t&&{body:{cartId:t}}))}}function Qt(e,t,n){t.forEach(t=>{qt(t)&&t.resolveIds.forEach(i=>{e.getFactory(i,!0)||e.register(i,()=>t(n))})})}!function(e){e.SignInFailed="CUSTOMER_STRATEGY_SIGN_IN_FAILED",e.SignInRequested="CUSTOMER_STRATEGY_SIGN_IN_REQUESTED",e.SignInSucceeded="CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED",e.SignOutFailed="CUSTOMER_STRATEGY_SIGN_OUT_FAILED",e.SignOutRequested="CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED",e.SignOutSucceeded="CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED",e.ExecutePaymentMethodCheckoutFailed="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_FAILED",e.ExecutePaymentMethodCheckoutRequested="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_REQUESTED",e.ExecutePaymentMethodCheckoutSucceeded="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_SUCCEEDED",e.InitializeFailed="CUSTOMER_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="CUSTOMER_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="CUSTOMER_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED"}($t||($t={}));class Xt{constructor(e,t,n){this._strategyRegistry=e,this._strategyRegistryV2=t,this._paymentIntegrationService=n}signIn(e,t){return m.create(n=>{const i=t&&t.methodId,r={methodId:i};n.next(l($t.SignInRequested,void 0,r)),this._getStrategy(i).signIn(e,t).then(()=>{n.next(l($t.SignInSucceeded,void 0,r)),n.complete()}).catch(e=>{n.error(h($t.SignInFailed,e,r))})})}signOut(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l($t.SignOutRequested,void 0,i)),this._getStrategy(n).signOut(e).then(()=>{t.next(l($t.SignOutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h($t.SignOutFailed,e,i))})})}executePaymentMethodCheckout(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l($t.ExecutePaymentMethodCheckoutRequested,void 0,i)),this._getStrategy(n).executePaymentMethodCheckout(e).then(()=>{t.next(l($t.ExecutePaymentMethodCheckoutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h($t.ExecutePaymentMethodCheckoutFailed,e,i))})})}initialize(e){return t=>m.create(n=>{var i;const r=t.getState(),o=e&&e.methodId,a={methodId:o};if(Qt(this._strategyRegistryV2,null!==(i=null==e?void 0:e.integrations)&&void 0!==i?i:[],this._paymentIntegrationService),o&&r.customerStrategies.isInitialized(o))return n.complete();n.next(l($t.InitializeRequested,void 0,a)),this._getStrategy(o).initialize(e).then(()=>{n.next(l($t.InitializeSucceeded,void 0,a)),n.complete()}).catch(e=>{n.error(h($t.InitializeFailed,e,a))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=e&&e.methodId,o={methodId:r};if(r&&!i.customerStrategies.isInitialized(r))return n.complete();n.next(l($t.DeinitializeRequested,void 0,o)),this._getStrategy(r).deinitialize(e).then(()=>{n.next(l($t.DeinitializeSucceeded,void 0,o)),n.complete()}).catch(e=>{n.error(h($t.DeinitializeFailed,e,o))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l($t.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l($t.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h($t.WidgetInteractionFailed,e,i))})})}_getStrategy(e){let t;try{t=this._strategyRegistryV2.get({id:e||""})}catch(n){t=this._strategyRegistry.get(e)}return t}}function en(e,t=[]){return Array.isArray(t)?Lt([...e,...t]):function(e,t){const n=ie(me(t,e=>!e)),i=ie(L(t));return Lt([...R(e,n),...i])}(e,t)}class tn{constructor(e){this._requestSender=e}loadCheckout(e,{params:{include:t}={},timeout:n}={}){const i=`/api/storefront/checkout/${e}`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.get(i,{params:{include:en(zt,t)},headers:r,timeout:n}).catch(e=>{if(e.status>=400&&e.status<500)throw new At(e);throw e})}updateCheckout(e,t,{params:{include:n}={},timeout:i}={}){const r=`/api/storefront/checkout/${e}`,o=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.put(r,{params:{include:en(zt,n)},body:t,headers:o,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}!function(e){e.LoadCheckoutRequested="LOAD_CHECKOUT_REQUESTED",e.LoadCheckoutSucceeded="LOAD_CHECKOUT_SUCCEEDED",e.LoadCheckoutFailed="LOAD_CHECKOUT_FAILED",e.UpdateCheckoutRequested="UPDATE_CHECKOUT_REQUESTED",e.UpdateCheckoutSucceeded="UPDATE_CHECKOUT_SUCCEEDED",e.UpdateCheckoutFailed="UPDATE_CHECKOUT_FAILED"}(Yt||(Yt={})),function(e){e.HydrateInitialState="HYDRATE_INITIAL_STATE"}(Kt||(Kt={}));var nn;class rn{constructor(e,t,n){this._checkoutRequestSender=e,this._configActionCreator=t,this._formFieldsActionCreator=n}loadCheckout(e,t){return()=>g(C(l(Yt.LoadCheckoutRequested)),I(this._configActionCreator.loadConfig({useCache:!0,timeout:null==t?void 0:t.timeout,params:{checkoutId:e}}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==t?void 0:t.timeout})),f(()=>this._checkoutRequestSender.loadCheckout(e,t).then(({body:e})=>l(Yt.LoadCheckoutSucceeded,this._transformCustomerAddresses(e))))).pipe(P(e=>Ke(Yt.LoadCheckoutFailed,e)))}loadDefaultCheckout(e){return t=>g(C(l(Yt.LoadCheckoutRequested)),I(this._configActionCreator.loadConfig({useCache:!0,timeout:null==e?void 0:e.timeout}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==e?void 0:e.timeout})),f(()=>{return n=this,i=void 0,o=function*(){const n=t.getState().config.getContextConfig();if(!n||!n.checkoutId)throw new ot(tt.MissingCheckoutConfig);const{body:i}=yield this._checkoutRequestSender.loadCheckout(n.checkoutId,e);return l(Yt.LoadCheckoutSucceeded,this._transformCustomerAddresses(i))},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Ke(Yt.LoadCheckoutFailed,e)))}updateCheckout(e,t){return n=>new m(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);i.next(l(Yt.UpdateCheckoutRequested)),this._checkoutRequestSender.updateCheckout(r.id,e,t).then(({body:e})=>{i.next(l(Yt.UpdateCheckoutSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Yt.UpdateCheckoutFailed,e))})})}loadCurrentCheckout(e){return t=>{const n=t.getState().checkout.getCheckout();if(!n)throw new ot(tt.MissingCheckout);return this.loadCheckout(n.id,e)(t)}}hydrateInitialState(e){return{type:Kt.HydrateInitialState,payload:e}}_transformCustomerAddresses(e){return Object.assign(Object.assign({},e),{customer:Object.assign(Object.assign({},e.customer),{addresses:e.customer.addresses.map(e=>Object.assign(Object.assign({},e),{shouldSaveAddress:!1}))})})}}!function(e){e.LoadFormFieldsRequested="LOAD_FORM_FIELDS_REQUESTED",e.LoadFormFieldsSucceeded="LOAD_FORM_FIELDS_SUCCEEDED",e.LoadFormFieldsFailed="LOAD_FORM_FIELDS_FAILED"}(nn||(nn={}));var on;class an{constructor(e){this._formFieldsRequestSender=e}loadFormFields(e){return g(C(l(nn.LoadFormFieldsRequested)),f(()=>{return t=this,n=void 0,r=function*(){const{body:t}=yield this._formFieldsRequestSender.loadFields(e);return l(nn.LoadFormFieldsSucceeded,t)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r})).pipe(P(e=>Ke(nn.LoadFormFieldsFailed,e)))}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Ct],an.prototype,"loadFormFields",null);class sn{constructor(e){this._requestSender=e}loadFields({timeout:e}={}){return this._requestSender.get("/api/storefront/form-fields",{timeout:e,headers:Object.assign({Accept:lt.JsonV1,"X-API-INTERNAL":Tt},et)})}}class dn extends rt{constructor(){super("You haven't complete our spam protection challenge. Please try again."),this.name="SpamProtectionChallengeNotCompletedError",this.type="spam_protection_challenge_not_completed"}}class cn extends rt{constructor(){super("We were not able to complete your spam protection verification. Please try again."),this.name="SpamProtectionFailedError",this.type="spam_protection_failed"}}!function(e){e.InitializeFailed="SPAM_PROTECTION_INITIALIZE_FAILED",e.InitializeSucceeded="SPAM_PROTECTION_INITIALIZE_SUCCEEDED",e.InitializeRequested="SPAM_PROTECTION_INITIALIZE_REQUESTED",e.VerifyCheckoutRequested="SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED",e.VerifyCheckoutSucceeded="SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED",e.VerifyCheckoutFailed="SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED",e.ExecuteRequested="SPAM_PROTECTION_EXECUTE_REQUESTED",e.ExecuteSucceeded="SPAM_PROTECTION_EXECUTE_SUCCEEDED",e.ExecuteFailed="SPAM_PROTECTION_EXECUTE_FAILED"}(on||(on={}));var ln,un,hn,pn=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class mn{constructor(e,t){this._googleRecaptcha=e,this._requestSender=t}initialize(e){return t=>g(C(l(on.InitializeRequested,void 0)),f(()=>pn(this,void 0,void 0,function*(){const n=e?e.containerId:"spamProtectionContainer";if(document.getElementById(n)&&this._googleRecaptcha.reset(n),!e&&!document.getElementById(n)){const e=document.createElement("div");e.setAttribute("id",n),document.body.appendChild(e)}const i=t.getState().config.getStoreConfigOrThrow().checkoutSettings.googleRecaptchaSitekey;return yield this._googleRecaptcha.load(n,i),l(on.InitializeSucceeded)}))).pipe(P(e=>Ke(on.InitializeFailed,e)))}verifyCheckoutSpamProtection(){return e=>f(()=>{const t=e.getState().checkout.getCheckout();if(!t)throw new ot(tt.MissingCheckout);return g(C(l(on.VerifyCheckoutRequested)),_(this.execute()(e)).pipe(M(e=>Wt(e)&&e.payload?_(this._requestSender.validate(t.id,e.payload.token)).pipe(M(({body:t})=>g(C(e),C(l(on.VerifyCheckoutSucceeded,t))))):C(e)))).pipe(P(e=>Ke(on.VerifyCheckoutFailed,e)))})}execute(){return e=>g(C(l(on.ExecuteRequested)),this.initialize()(e),this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>pn(this,void 0,void 0,function*(){if(e instanceof dn)throw e;if(e||!t)throw new cn;return l(on.ExecuteSucceeded,{token:t})})))).pipe(P(e=>Ke(on.ExecuteFailed,e)))}}class yn{constructor(e=window){this._window=e}create(e){return new this._window.MutationObserver(e)}}!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"}(ln||(ln={}));class gn extends rt{constructor(e){super(function(e){switch(e){case ln.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ln.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ln.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ln.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"}}class fn extends rt{constructor(){super("Spam protection is not loaded. Please try again."),this.name="SpamProtectionNotLoadedError",this.type="spam_protection_failed"}}class vn{constructor(e,t){this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=Pe((e,t,n)=>{const i=new y;if(!n)throw new Error;return this._widgetId=e.render(n.id,{sitekey:t,size:"invisible",callback:()=>{i.next({token:e.getResponse(this._widgetId)}),e.reset(this._widgetId)},"error-callback":()=>{i.next({error:new cn})}}),i},{isEqual:(e,t)=>e===t})}load(e,t){return this.googleRecaptchaScriptLoader.load().then(n=>{n&&(this._event$=this._memoized(n,t,document.getElementById(e)),this._recaptcha=n)}).catch(e=>{throw e})}reset(e){var t;const n=document.getElementById(e);null==n||n.remove(),null===(t=this._recaptcha)||void 0===t||t.reset(this._widgetId)}execute(){return f(()=>{const e=this._event$,t=this._recaptcha;if(!e||!t)throw new gn(ln.SpamProtectionNotInitialized);return f(()=>{const e=document.querySelector('iframe[src*="bframe"]');return e?C(e):b(new fn)}).pipe(k(e=>e.pipe(O(250),M((e,t)=>t<28?C(e):b(e)))),M(n=>(this._watchRecaptchaChallengeWindow(e,n),t.execute(this._widgetId),e)),P(e=>C({error:e})))})}_watchRecaptchaChallengeWindow(e,t){const n=t.parentElement;if(!n)throw new fn;const i=n.parentElement;if(!i)throw new fn;this.mutationObserverFactory.create(()=>{"hidden"===i.style.visibility&&e.next({error:new dn})}).observe(i,{attributes:!0,attributeFilter:["style"]})}}class _n{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise}_loadScript(){const e="initRecaptcha",t=[`onload=${e}`,"render=explicit"].join("&");return new Promise((n,i)=>{this._window[e]=()=>n(this._window.grecaptcha),this._scriptLoader.loadScript(`//www.google.com/recaptcha/api.js?${t}`).catch(e=>{this._loadPromise=void 0,i(e)})})}}function Sn(e){return new vn(new _n(e),new yn)}class In{constructor(e){this._requestSender=e}validate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/spam-protection`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(i,{body:{token:t},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}class wn{constructor(e,t){this._store=e,this._customerActionCreator=t}signIn(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))}signOut(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}function Cn(e){if(!/^(https?:)?\/\//.test(e))throw new Vt("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}class bn extends rt{constructor(e){super(e||"Unable to proceed due to no extension configured for this region."),this.name="ExtensionNotFoundError",this.type="extension_not_found"}}function Pn(e,t){return e.type===t}!function(e){e.LoadExtensionsRequested="LOAD_EXTENSIONS_REQUESTED",e.LoadExtensionsSucceeded="LOAD_EXTENSIONS_SUCCEEDED",e.LoadExtensionsFailed="LOAD_EXTENSIONS_FAILED",e.RenderExtensionRequested="RENDER_EXTENSION_REQUESTED",e.RenderExtensionSucceeded="RENDER_EXTENSION_SUCCEEDED",e.RenderExtensionFailed="RENDER_EXTENSION_FAILED"}(un||(un={}));class On{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":Cn(e).origin}post(e,t){const n=this._targetWindow;if(window===n)return;if(!n)throw new Error("Unable to post message because target window is not set.");const i=t&&S(window,"message").pipe(A(e=>e.origin===this._targetOrigin&&Pn(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),T(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),z(1)).toPromise();return n.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),i}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}function En(e){var t;const n=null===(t=document.querySelector(`[data-extension-id="${e.id}"]`))||void 0===t?void 0:t.querySelector("iframe");if(!(null==n?void 0:n.contentWindow))throw new bn(`Unable to post due to no extension rendered for ID: ${e.id}.`);return new On(e.url,n.contentWindow)}!function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(hn||(hn={}));class An{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}class Tn extends rt{constructor(e){super(e||"Unable to proceed because the required element is unexpectedly detached from the page."),this.name="UnexpectedDetachmentError",this.type="unexpected_detachment"}}var kn;class Dn{constructor(e){this._mutationObserver=e}ensurePresence(e,t){return n=this,i=void 0,o=function*(){const n=new An(t),i=this._mutationObserver.create(t=>{t.forEach(t=>{0!==Array.from(t.removedNodes).filter(t=>e.some(e=>t===e||t.contains(e))).length&&n.cancel(new Tn)})});i.observe(document.body,{childList:!0,subtree:!0});try{const e=yield n.promise;return i.disconnect(),e}catch(e){throw i.disconnect(),e}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function Mn(e,t){const{iframeResizer:n}=Ve(785);return n(e,t)}class zn extends rt{constructor(e){super(e||"Unable to load an extension"),this.name="ExtensionNotLoadedError",this.type="extension_not_loaded"}}!function(e){e.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",e.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",e.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(kn||(kn={}));class xn{constructor(e){this._options=e}createFrame(e,t,n,i){const r=document.getElementById(t),{timeout:o=6e4}=this._options||{};if(!r)throw new zn("Unable to embed the iframe because the container element could not be found.");const a=document.createElement("iframe");return a.src=e,a.style.border="none",a.style.display="none",a.style.width="100%",r.appendChild(a),this._toResizableFrame(a,o,n,i).catch(e=>{throw r.removeChild(a),e})}_toResizableFrame(e,t,n,i){return r=this,o=void 0,s=function*(){const r=new Dn(new yn),o=new Promise((r,o)=>{const a=window.setTimeout(()=>{try{i()}catch(e){e instanceof Error&&console.error(`Extension rendering timed out after ${t}ms, and the callback function could not be executed. Error: ${e.message}`)}o(new zn("Unable to load the extension because the content could not be loaded."))},t),s=t=>{if(t.origin===Cn(e.src).origin&&Pn(t.data,kn.ResizeIframe)){e.style.display="";const t=Mn({autoResize:!1,scrolling:!1,sizeWidth:!1,heightCalculationMethod:"bodyOffset",initCallback:n},e);d(),r(t[t.length-1])}},d=()=>{window.removeEventListener("message",s),window.clearTimeout(a)};window.addEventListener("message",s)});return r.ensurePresence([e],o)},new((a=void 0)||(a=Promise))(function(e,t){function n(e){try{d(s.next(e))}catch(e){t(e)}}function i(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(n,i)}d((s=s.apply(r,o||[])).next())});var r,o,a,s}}class Nn{constructor(e,t,n){this._containerId=e,this._extension=t,this._config=n;const{cartId:i,parentOrigin:r}=this._config;this._url=new URL(this._extension.url),this._url.searchParams.set("extensionId",this._extension.id),this._url.searchParams.set("cartId",i),this._url.searchParams.set("parentOrigin",r)}attach(){var e,t,n,i,r;return t=this,n=void 0,r=function*(){if(null===(e=document.querySelector(`[data-extension-id="${this._extension.id}"]`))||void 0===e?void 0:e.querySelector("iframe"))return;const t=new xn,n=e=>{En(this._extension).post({type:e})};this._iframe=yield t.createFrame(this._url.toString(),this._containerId,()=>{n(hn.ExtensionReady)},()=>{n(hn.ExtensionFailed)});const i=document.getElementById(this._containerId);null==i||i.setAttribute("data-extension-id",this._extension.id)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())})}detach(){this._iframe&&this._iframe.parentElement&&this._iframe.parentElement.removeChild(this._iframe)}}class Rn{constructor(e){this._requestSender=e}loadExtensions(e){return()=>m.create(t=>{t.next(l(un.LoadExtensionsRequested)),this._requestSender.loadExtensions(e).then(e=>{const n=e.body;t.next(l(un.LoadExtensionsSucceeded,n)),t.complete()}).catch(e=>{t.error(h(un.LoadExtensionsFailed,e))})})}renderExtension(e,t,n){return i=>m.create(r=>{return o=this,a=void 0,d=function*(){const o=i.getState(),{id:a}=o.cart.getCartOrThrow(),{links:{checkoutLink:s}}=o.config.getStoreConfigOrThrow(),d=o.extensions.getExtensionByRegion(t);try{if(!d)throw new bn(`Unable to proceed due to no extension configured for the region: ${t}.`);if(r.next(l(un.RenderExtensionRequested)),"worker"===d.type){const e=function(e){if(!window.Worker)throw new Error("Unable to load the extension's web worker: your browser does not support Web Workers.");try{const t=URL.createObjectURL(new Blob([`importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,"${e}"))))(importScripts);importScripts("${e}")`],{type:"text/javascript"}));return new Worker(t)}catch(e){throw new Error("Unable to load the extension's web worker")}}(d.url);n.add(d.id,e)}else{const t=new Nn(e,d,{cartId:a,parentOrigin:Cn(s).origin});yield t.attach()}r.next(l(un.RenderExtensionSucceeded)),r.complete()}catch(e){r.error(h(un.RenderExtensionFailed,e))}},new((s=void 0)||(s=Promise))(function(e,t){function n(e){try{r(d.next(e))}catch(e){t(e)}}function i(e){try{r(d.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s(function(e){e(r)})).then(n,i)}r((d=d.apply(o,a||[])).next())});var o,a,s,d})}}class Fn{constructor(e){this._requestSender=e}loadExtensions({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-extensions",{timeout:e,headers:Object.assign({Accept:lt.JsonV1},et),params:t})}}const Ln=function(e,t,n){return t&&n?jn(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,jn(e.prototype,n,i))}),t}(e)};function jn(e,t,n){if("function"!=typeof n.value)return n;let i=n.value;return{get(){const e=i.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=e}}}var Bn,Un;class qn{constructor(e){this._worker=e,this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,this._worker.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,this._worker.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["context"]);this.trigger(i,n)}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Ln],qn.prototype,"_handleMessage",null);class Vn{constructor(e,t){this._worker=e,this._context=t}post(e){if(!this._worker)throw new Error("WorkerPoster: Worker is not initialized or creation failed. Cannot post message.");this._worker.postMessage(Object.assign(Object.assign({},e),{context:this._context}))}}class Gn extends rt{constructor(e){super(e||"Unable to proceed due to unsupported extension command."),this.name="UnsupportedExtensionCommandError",this.type="unsupported_extension_command_error"}}class Hn extends rt{constructor(e){super(e||"Unable to proceed due to unsupported extension query."),this.name="UnsupportedExtensionQueryError",this.type="unsupported_extension_query_error"}}!function(e){e.ReloadCheckout="EXTENSION:RELOAD_CHECKOUT",e.ShowLoadingIndicator="EXTENSION:SHOW_LOADING_INDICATOR",e.SetIframeStyle="EXTENSION:SET_IFRAME_STYLE",e.ReRenderShippingForm="EXTENSION:RE_RENDER_SHIPPING_FORM",e.ReRenderShippingStep="EXTENSION:RE_RENDER_SHIPPING_STEP"}(Bn||(Bn={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(Un||(Un={}));class Wn{constructor(e={},t={},n={}){this._workers=e,this._commandListeners=t,this._queryListeners=n}add(e,t){this._workers[e]=t}listenForCommand(e,t,n){const i=this._getWorkerById(e);this._commandListeners[e]||(this._commandListeners[e]=new qn(i));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getWorkerById(e);this._queryListeners[e]||(this._queryListeners[e]=new qn(i));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()}post(e,t){if(!this._workers[e])throw new Error(`Worker with extensionId ${e} not found`);new Vn(this._workers[e],e).post(t)}clearCacheById(e){delete this._workers[e]}_getWorkerById(e){const t=this._workers[e];if(!t)throw new bn(`Worker with extensionId ${e} not found`);return t}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Gn}_validateQuery(e){if(Object.values(Un).includes(e))return e;throw new Hn}}function $n(e){return Cn(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,`www.${e.hostname}`))}var Yn;class Kn{constructor(e){this._sourceOrigins=[Cn(e).origin,$n(Cn(e)).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!Pn(e.data,e.data.type))return;const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["context"]);this.trigger(i,n)}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Ln],Kn.prototype,"_handleMessage",null);class Jn{constructor(e,t,n={},i={},r={}){this._store=e,this._workerExtensionMessenger=t,this._commandListeners=n,this._queryListeners=i,this._posters=r}clearCacheByRegion(e){const t=this._getExtensionByRegion(e);"worker"!==t.type?this.clearCacheById(t.id):this._workerExtensionMessenger.clearCacheById(t.id)}clearCacheById(e){const t=this._getExtensionById(e);"worker"!==t.type?(this._commandListeners[e]&&delete this._commandListeners[e],this._queryListeners[e]&&delete this._queryListeners[e],this._posters[e]&&delete this._posters[e]):this._workerExtensionMessenger.clearCacheById(t.id)}listenForCommand(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForCommand(e,t,n);this._commandListeners[e]||(this._commandListeners[e]=new Kn(i.url));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForQuery(e,t,n);this._queryListeners[e]||(this._queryListeners[e]=new Kn(i.url));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){"worker"!==this._getExtensionById(e).type?(this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()):this._workerExtensionMessenger.stopListen(e)}post(e,t){try{const n=this._getExtensionById(e);if("worker"===n.type)return void this._workerExtensionMessenger.post(e,t);this._posters[e]||(this._posters[e]=En(n)),this._posters[e].post(t)}catch(n){this.clearCacheById(e),console.log(`Unable to post event to extension(${e}) because extension iframe is not mounted.\nThe event that could not be delivered:`,t)}}_getExtensionById(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.id===e);if(!n)throw new bn(`Unable to proceed due to no extension found for ID: ${e}.`);return n}_getExtensionByRegion(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.region===e);if(!n)throw new bn(`Unable to proceed due to no extension found for region: ${e}.`);return n}_getExtensions(){if(this._extensions)return;const{extensions:{getExtensions:e}}=this._store.getState();if(this._extensions=e(),!this._extensions)throw new bn("Extension configurations not found.")}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Gn}_validateQuery(e){if(Object.values(Un).includes(e))return e;throw new Hn}}class Zn{constructor(e,t,n){this._store=e,this._extensionMessenger=t,this._subscribers=n,this._subscribed={},this._unsubscribers={},this._listeners={}}listen(){var e;const{data:{getExtensions:t}}=this._store.getState();null===(e=t())||void 0===e||e.forEach(e=>{if(this._listeners[e.id])return;const t=new Kn(e.url);t.addListener(kn.Subscribe,this._handleSubscribe.bind(this)),t.addListener(kn.Unsubscribe,this._handleUnsubscribe.bind(this)),t.listen(),this._listeners[e.id]=t})}broadcast(e){var t;const{data:{getExtensions:n}}=this._store.getState();null===(t=n())||void 0===t||t.forEach(t=>{this._subscribed[t.id]&&this._extensionMessenger.post(t.id,e)})}_handleSubscribe({payload:{eventType:e,extensionId:t}}){this._subscribed[t]=!0,this._unsubscribers[e]||(this._unsubscribers[e]=this._subscribers[e](this._store,this))}_handleUnsubscribe({payload:{eventType:e,extensionId:t}}){var n,i;delete this._subscribed[t],Object.keys(this._subscribed).length||(null===(i=(n=this._unsubscribers)[e])||void 0===i||i.call(n),delete this._unsubscribers[e])}}!function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}(Yn||(Yn={}));const Qn=(e,t)=>{var n;const{data:{getConsignments:i}}=e.getState();let r=null!==(n=i())&&void 0!==n?n:[];return e.subscribe(({data:{getConsignments:e}})=>{var n;const i=null!==(n=e())&&void 0!==n?n:[];i!==r&&(t.broadcast({type:Yn.ConsignmentsChanged,payload:{consignments:i,previousConsignments:r}}),r=i)},({data:{getConsignments:e}})=>e())};class Xn 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}}var ei,ti;!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"}(ei||(ei={}));class ni extends Xn{constructor(e){super(function(e){switch(e){case ei.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case ei.MissingCart:return"Unable to proceed because cart data is unavailable.";case ei.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case ei.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case ei.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case ei.MissingCheckoutConfig:case ei.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case ei.MissingOrder:return"Unable to proceed because order data is unavailable.";case ei.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case ei.MissingPayment:return"Unable to proceed because payment data is unavailable.";case ei.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case ei.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case ei.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"}}function ii(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}!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"}(ti||(ti={}));class ri extends Xn{constructor(e){super(function(e){switch(e){case ti.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ti.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ti.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ti.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"}}const oi={de:"eu",jp:"fe",uk:"eu",us:"na"};var ai,si,di,ci,li,ui;!function(e){e.en_US="en_US",e.en_GB="en_GB",e.de_DE="de_DE",e.fr_FR="fr_FR",e.it_IT="it_IT",e.es_ES="es_ES",e.ja_JP="ja_JP"}(ai||(ai={})),function(e){e.Home="Home",e.Product="Product",e.Cart="Cart",e.Checkout="Checkout",e.Other="Other"}(si||(si={})),function(e){e.USD="USD",e.EUR="EUR",e.GBP="GBP",e.JPY="JPY"}(di||(di={})),function(e){e.PayAndShip="PayAndShip",e.PayOnly="PayOnly"}(ci||(ci={})),function(e){e.Gold="Gold",e.LightGray="LightGray",e.DarkGray="DarkGray"}(li||(li={})),function(e){e.C0001="C0001"}(ui||(ui={}));var hi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pi{constructor(e){this.amazonPayV2ScriptLoader=e}initialize(e){return hi(this,void 0,void 0,function*(){this.amazonPayV2SDK=yield this.amazonPayV2ScriptLoader.load(e),this.buttonParentContainer=this.buttonParentContainer||this.createAmazonPayButtonParentContainer()})}deinitialize(){var e;return this.amazonPayV2Button=void 0,null===(e=this.buttonParentContainer)||void 0===e||e.remove(),this.buttonParentContainer=void 0,this.amazonPayV2SDK=void 0,Promise.resolve()}bindButton(e,t,n){this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${e}`,{amazonCheckoutSessionId:t,changeAction:n})}createButton(e,t){this.amazonPayV2Button=this.getAmazonPayV2SDK().Pay.renderButton(`#${e}`,t)}prepareCheckout(e){const t=this.prepareRequestConfig(e);this.getAmazonPayV2Button().onClick(()=>{this.getAmazonPayV2Button().initCheckout(t)})}prepareCheckoutWithCreationRequestConfig(e){this.getAmazonPayV2Button().onClick(()=>hi(this,void 0,void 0,function*(){const t=yield e();if(t){const e=this.prepareRequestConfig(t.createCheckoutSessionConfig,t.estimatedOrderAmount,t.productType);this.getAmazonPayV2Button().initCheckout(e)}}))}signout(){return hi(this,void 0,void 0,function*(){return this.amazonPayV2SDK&&this.amazonPayV2SDK.Pay.signout(),Promise.resolve()})}renderAmazonPayButton({buttonColor:e,checkoutState:t,containerId:n,decoupleCheckoutInitiation:i=!1,methodId:r,options:o,placement:a,isButtonMicroTextDisabled:s=!1}){const d=document.querySelector(`#${n}`);if(!d)return;const{id:c}=d.appendChild(this.getButtonParentContainer());o&&s&&(o.design=ui.C0001);const l=null!=o?o:this.getAmazonPayV2ButtonOptions(t,r,a,i,e);return this.createButton(c,l),this.getButtonParentContainer()}updateBuyNowFlowFlag(e){this.isBuyNowFlow=Boolean(e)}isPh4Enabled(e,t){const n=!!e["PROJECT-3483.amazon_pay_ph4"],i=!!e["INT-6885.amazon_pay_ph4_us_only"];return n&&i?"US"===t:n}prepareRequestConfig(e,t,n){const{publicKeyId:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["publicKeyId"]);return Object.assign(Object.assign({createCheckoutSessionConfig:this.isEnvironmentSpecific(i)?r:e},t&&{estimatedOrderAmount:t}),n&&{productType:n})}createAmazonPayButtonParentContainer(){const e=Math.random().toString(16).substr(-4),t=document.createElement("div");return t.id=`amazonpay_button_parent_container_${e}`,t}getAmazonPayV2ButtonOptions(e,t,n,i=!1,r=li.Gold){var o;const{getCart:a,getCheckout:s,getStoreConfigOrThrow:d,getPaymentMethodOrThrow:c}=this.getCheckoutState(e),{config:{merchantId:l,testMode:u},initializationData:h}=c(t);if(!h)throw new ni(ei.MissingPaymentMethod);const{checkoutLanguage:p,checkoutSessionMethod:m,createCheckoutSessionConfig:y,extractAmazonCheckoutSessionId:g,ledgerCurrency:f,publicKeyId:v="",isButtonMicroTextDisabled:_}=h;if(!l||!f)throw new ni(ei.MissingPaymentMethod);const S=Object.assign({merchantId:l,ledgerCurrency:f,checkoutLanguage:p,placement:n,buttonColor:r},_?{design:ui.C0001}:{});if(this.isBuyNowFlow)return Object.assign(Object.assign({},S),{sandbox:!!u});const I=a();S.productType=I&&0===function(e){return t=e.lineItems.physicalItems.filter(e=>!e.addedByPromotion),ye(t,(e,t)=>e+t.quantity,0);var t}(I)?ci.PayOnly:ci.PayAndShip;const{checkoutSettings:{features:w},storeProfile:{shopPath:C,storeCountryCode:b}}=d();if(this.isPh4Enabled(w,b)){if(!y)throw new ni(ei.MissingPaymentMethod);const e=null===(o=s())||void 0===o?void 0:o.outstandingBalance.toString(),t=null==I?void 0:I.currency.code,n=Object.assign({},S);let r;return this.isEnvironmentSpecific(v)?(n.publicKeyId=v,r=y):(n.sandbox=!!u,r=Object.assign(Object.assign({},y),{publicKeyId:v})),i||(n.createCheckoutSessionConfig=r),e&&t&&(n.estimatedOrderAmount={amount:e,currencyCode:t}),n}const P={method:m,url:`${C}/remote-checkout/${t}/payment-session`,extractAmazonCheckoutSessionId:g};return Object.assign(Object.assign({},S),{createCheckoutSession:P,sandbox:!!u})}isEnvironmentSpecific(e){return/^(SANDBOX|LIVE)/.test(e)}getAmazonPayV2SDK(){return this.getOrThrow(this.amazonPayV2SDK)}getButtonParentContainer(){return this.getOrThrow(this.buttonParentContainer)}getAmazonPayV2Button(){return this.getOrThrow(this.amazonPayV2Button)}getOrThrow(e){return ii(e,()=>new ri(ti.PaymentNotInitialized))}getCheckoutState(e){return"object"==typeof(t=e)&&null!==t&&"cart"in t&&"checkout"in t&&"config"in t&&"paymentMethods"in t?{getCart:e.cart.getCart,getCheckout:e.checkout.getCheckout,getStoreConfigOrThrow:e.config.getStoreConfigOrThrow,getPaymentMethodOrThrow:t=>e.paymentMethods.getPaymentMethodOrThrow(t)}:e;var t}}class mi extends Xn{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"}}class yi{constructor(e,t=window){this.scriptLoader=e,this.windowWithAmazonPay=t}load(e){return t=this,n=void 0,r=function*(){const{initializationData:t}=e,n=(null==t?void 0:t.region)||"us",i=oi[n];if(yield this.scriptLoader.loadScript(`https://static-${i}.payments-amazon.com/checkout.js`),!this.windowWithAmazonPay.amazon)throw new mi;return this.windowWithAmazonPay.amazon},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}function gi(){return new pi(new yi(a()))}function fi(e,t){return Object.assign(e,{resolveIds:t})}class vi extends Xn{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class _i extends Xn{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var Si=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ii{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return Si(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t||!(null==n?void 0:n.container))throw new vi('Unable to proceed because "methodId" or "containerId" argument is not provided.');let i;try{i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}catch(e){yield this.paymentIntegrationService.loadPaymentMethod(t),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}yield this.amazonPayV2PaymentProcessor.initialize(i),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:n.container,methodId:t,placement:si.Checkout})})}deinitialize(){return Si(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize()})}signIn(){throw new _i('In order to sign in via Amazon, the shopper must click on "Amazon Pay" button.')}signOut(e){return Si(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentId();t&&(yield this.amazonPayV2PaymentProcessor.signout(),yield this.paymentIntegrationService.remoteCheckoutSignOut(t.providerId,e))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}}const wi=fi(e=>new Ii(e,gi()),[{id:"amazonpay"}]);function Ci(e,t,n=!0){var i;return null!==(i=e[t])&&void 0!==i?i:n}const bi="3.128.0",Pi="3.123.2",Oi="3.106.0";class Ei{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()||(Ci(t,"PAYPAL-5809.braintree_hosted_fields_fix_version")?bi:Ci(t,"PAYPAL-5636.update_braintree_sdk_version")?Pi:Oi)}getPreloadedSDKVersion(){const e=this.braintreeWindow.braintree;if(e){const t=j(Object.values(e),e=>!!e.VERSION);return null==t?void 0:t.VERSION}}}class Ai extends Xn{constructor(e){super(e||"Unsupported browser error"),this.name="UnsupportedBrowserError",this.type="unsupported_browser"}}var Ti,ki,Di,Mi,zi,xi,Ni;function Ri(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"}(Ti||(Ti={})),function(e){e.Completed="COMPLETED",e.Pending="PENDING",e.Failed="FAILED"}(ki||(ki={})),function(e){e.TRUSTLY="trustly"}(Di||(Di={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="cancelled",e.UNRECOGNIZED="unrecognized"}(Mi||(Mi={})),function(e){e.Customer="CUSTOMER",e.Merchant="MERCHANT",e.Network="NETWORK",e.Internal="INTERNAL",e.Unknown="UNKNOWN"}(zi||(zi={})),function(e){e.KountNotEnabled="DATA_COLLECTOR_KOUNT_NOT_ENABLED"}(xi||(xi={})),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"}(Ni||(Ni={}));var Fi,Li,ji,Bi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ui{constructor(e){this.braintreeScriptLoader=e}initialize(e){this.setClientToken(e)}deinitialize(){return Bi(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollector),this.dataCollector=void 0})}getClient(){return Bi(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 Bi(this,void 0,void 0,function*(){const t={deviceData:void 0,teardown:()=>Promise.resolve()};if(!this.dataCollector)try{const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadDataCollector(),i=Object.assign({client:t,kount:!0},e);this.dataCollector=yield n.create(i)}catch(e){if(Ri(e)&&e.code===xi.KountNotEnabled)return t;throw e}return this.dataCollector})}getBraintreeGooglePayment(){return Bi(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 Bi(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 Bi(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment){const[t,n]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadLocalPayment()]);this.braintreeLocalPayment=yield new Promise((i,r)=>{n.create({client:t,merchantAccountId:e},(e,t)=>{e&&r(e),i(t)})})}return this.braintreeLocalPayment})}getUsBankAccount(){return Bi(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 Bi(this,void 0,void 0,function*(){return this.visaCheckoutSDK||(this.visaCheckoutSDK=yield this.braintreeScriptLoader.loadVisaCheckoutSdk(e)),this.visaCheckoutSDK})}getVenmoCheckoutOrThrow(){return Bi(this,void 0,void 0,function*(){if(!this.braintreeVenmo){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadVenmoCheckout(),n={client:e,allowDesktop:!0,paymentMethodUsage:"multi_use"},i=yield t.create(n);if(!i.isBrowserSupported())throw new Ai;this.braintreeVenmo=i}return this.braintreeVenmo})}setClientToken(e){this.clientToken=e}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ti.PaymentNotInitialized);return this.clientToken}teardownModule(e){return e?e.teardown():Promise.resolve()}}!function(e){e.Sandbox="sandbox",e.Production="production"}(Fi||(Fi={})),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"}(Li||(Li={})),function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(ji||(ji={}));const qi={[Oi]:{[Li.Client]:"sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt",[Li.PaypalCheckout]:"sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O",[Li.Paypal]:"sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+",[Li.LocalPayment]:"sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT",[Li.DataCollector]:"sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV",[Li.UsBankAccount]:"sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ",[Li.GooglePayment]:"sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe",[Li.ThreeDSecure]:"sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB",[Li.VisaCheckout]:"sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT",[Li.Venmo]:"sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov",[Li.HostedFields]:"sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy",[Li.Fastlane]:"sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa"},[Pi]:{[Li.Client]:"sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO",[Li.PaypalCheckout]:"sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/",[Li.Paypal]:"sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt",[Li.LocalPayment]:"sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH",[Li.DataCollector]:"sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO",[Li.UsBankAccount]:"sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW",[Li.GooglePayment]:"sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO",[Li.ThreeDSecure]:"sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym",[Li.VisaCheckout]:"sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS",[Li.Venmo]:"sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU",[Li.HostedFields]:"sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P",[Li.Fastlane]:"sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y"},[bi]:{[Li.Client]:"sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq",[Li.PaypalCheckout]:"sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh",[Li.Paypal]:"sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH",[Li.LocalPayment]:"sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC",[Li.DataCollector]:"sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc",[Li.UsBankAccount]:"sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F",[Li.GooglePayment]:"sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i",[Li.ThreeDSecure]:"sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D",[Li.VisaCheckout]:"sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv",[Li.Venmo]:"sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz",[Li.HostedFields]:"sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z",[Li.Fastlane]:"sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr"}};var Vi,Gi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hi{constructor(e,t,n){this.scriptLoader=e,this.braintreeHostWindow=t,this.braintreeSDKVersionManager=n}loadClient(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Client,"client.min.js")})}loadFastlane(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Fastlane,"fastlane.min.js")})}loadPaypalCheckout(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.PaypalCheckout,"paypal-checkout.min.js")})}loadPaypal(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Paypal,"paypal.min.js")})}loadLocalPayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.LocalPayment,"local-payment.min.js")})}loadDataCollector(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.DataCollector,"data-collector.min.js")})}loadUsBankAccount(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.UsBankAccount,"us-bank-account.min.js")})}loadGooglePayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.GooglePayment,"google-payment.min.js")})}load3DS(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.ThreeDSecure,"three-d-secure.min.js")})}loadVisaCheckout(){return this.loadBraintreeModuleOrThrow(Li.VisaCheckout,"visa-checkout.min.js")}loadVenmoCheckout(){return this.loadBraintreeModuleOrThrow(Li.Venmo,"venmo.min.js")}loadHostedFields(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.HostedFields,"hosted-fields.min.js")})}loadVisaCheckoutSdk(e){return Gi(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 mi;return this.braintreeHostWindow.V})})}loadBraintreeModuleOrThrow(e,t){return Gi(this,void 0,void 0,function*(){let n=this.getBraintreeModule(e);if(n)return n;const i=this.braintreeSDKVersionManager.getSDKVersion(),r=`//js.braintreegateway.com/web/${i}/js/${t}`,o=i in qi?this.getIntegrityValuesByModuleName(e,i):void 0;if(yield this.scriptLoader.loadScript(r,o?{async:!0,attributes:{integrity:o,crossorigin:"anonymous"}}:void 0),n=this.getBraintreeModule(e),!n)throw new mi;return n})}getBraintreeModule(e){var t;return null===(t=this.braintreeHostWindow.braintree)||void 0===t?void 0:t[e]}getIntegrityValuesByModuleName(e,t){const n=qi[t][e];if(!n)throw new Error("Unexpected fileName value");return n}}class Wi extends Xn{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}!function(e){e.BRAINTREE="braintree",e.BRAINTREE_FASTLANE="braintreeacceleratedcheckout"}(Vi||(Vi={}));var $i,Yi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}($i||($i={}));class Ki{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._onAuthorizeCallback=ce,this._onError=ce,this._onClick=ce,this._subTotalLabel=$i.Subtotal,this._shippingLabel=$i.Shipping,this._hasApplePaySession=!1}initialize(e){var t;return Yi(this,void 0,void 0,function*(){const{methodId:n,applepay:i}=e;if(!n||!i)throw new ni(ei.MissingPaymentMethod);const{container:r,shippingLabel:o,subtotalLabel:a,onError:s=ce,onClick:d=ce,onPaymentAuthorize:c}=i;this._shippingLabel=o||$i.Shipping,this._subTotalLabel=a||$i.Subtotal,this._onAuthorizeCallback=c,this._onError=s,this._onClick=d;let l=this._paymentIntegrationService.getState();yield this._applePayScriptLoader.loadSdk();try{this._paymentMethod=l.getPaymentMethodOrThrow(n)}catch(e){l=yield this._paymentIntegrationService.loadPaymentMethod(n),this._paymentMethod=l.getPaymentMethodOrThrow(n)}yield this._paymentIntegrationService.verifyCheckoutSpamProtection(),this._applePayButton=this._createButton(r),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===Vi.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken)})}deinitialize(){return Promise.resolve()}signIn(){throw new _i('In order to sign in via Apple, the shopper must click on "Apple Pay" button.')}signOut(){throw new _i("Need to do signout via apple.")}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}_createButton(e){const t=document.getElementById(e);if(!t)throw new vi("Unable to create sign-in button without valid container ID.");const n=this._createApplePayButtonElement();return t.appendChild(n),n}_createApplePayButtonElement(){const e=document.createElement("apple-pay-button");return e.setAttribute("buttonstyle","black"),e.setAttribute("type","plain"),e.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),e}_handleWalletButtonClick(e){if(e.preventDefault(),this._hasApplePaySession)return;this._onClick();const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new ni(ei.MissingPaymentMethod);const o=this._getBaseRequest(n,r,i,this._paymentMethod),a=this._sessionFactory.create(o);this._handleApplePayEvents(a,this._paymentMethod,i),a.begin(),this._hasApplePaySession=!0}_getBaseRequest(e,t,n,i){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=n,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=i,u=e.lineItems.physicalItems.length>0,h={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:[],total:u?{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"pending"}:{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"final"}};if(u)null===(r=h.requiredShippingContactFields)||void 0===r||r.push("postalAddress");else{const e=[{label:this._subTotalLabel,amount:`${t.subtotal.toFixed(d)}`}];t.taxes.forEach(t=>e.push({label:t.name,amount:`${t.amount.toFixed(d)}`})),h.lineItems=e}return h}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>Yi(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){this._onError(e)}}),e.onshippingcontactselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingContactSelected(e,n,t)}),e.onshippingmethodselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingMethodSelected(e,n,t)}),e.oncancel=()=>Yi(this,void 0,void 0,function*(){this._hasApplePaySession=!1;try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){return this._onError(new Wi)}}),e.onpaymentauthorized=n=>Yi(this,void 0,void 0,function*(){return this._onPaymentAuthorized(n,e,t)})}_handleShippingContactSelected(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const r=this._transformContactToAddress(n.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const{storeProfile:{storeName:o}}=t;let a=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:s}}=a.getCartOrThrow();let d=a.getCheckoutOrThrow();const c=null===(i=d.consignments[0].selectedShippingOption)||void 0===i?void 0:i.id,l=d.consignments[0].availableShippingOptions,u=null==l?void 0:l.find(({id:e})=>e===c),h=null==l?void 0:l.filter(e=>e.id!==c),p=u?[{label:u.description,amount:`${u.cost.toFixed(s)}`,detail:u.additionalDescription,identifier:u.id}]:[];if(h&&[...h.filter(e=>e.isRecommended),...h.filter(e=>!e.isRecommended)].forEach(e=>p.push({label:e.description,amount:`${e.cost.toFixed(s)}`,detail:e.additionalDescription,identifier:e.id})),!(l instanceof Array))throw new Error("Shipping options not available.");if(0===l.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:o,amount:`${d.grandTotal.toFixed(s)}`},[]);const m=l.find(e=>e.isRecommended),y=m?m.id:l[0].id,g=u?u.id:y;try{yield this._updateShippingOption(g)}catch(e){return this._onError(e)}a=this._paymentIntegrationService.getState(),d=a.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:o,amount:`${d.grandTotal.toFixed(s)}`},newLineItems:this._getUpdatedLineItems(d,s)})})}_handleShippingMethodSelected(e,t,n){return Yi(this,void 0,void 0,function*(){const{storeProfile:{storeName:i}}=t,{shippingMethod:{identifier:r}}=n;try{yield this._updateShippingOption(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const o=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:a}}=o.getCartOrThrow(),s=o.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:i,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_getUpdatedLineItems(e,t){const n=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>n.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),n.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),n}_updateShippingOption(e){return Yi(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return Yi(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/api/public/v1/payments/applepay/validate_merchant`,{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})})}_onPaymentAuthorized(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const{token:r,billingContact:o,shippingContact:a}=e.payment,s=this._paymentIntegrationService.getState().getCartOrThrow().lineItems.physicalItems.length>0;let d;(null===(i=n.initializationData)||void 0===i?void 0:i.gateway)===Vi.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:r.paymentData,payment_method:r.paymentMethod,transaction_id:r.transactionIdentifier}}}},l=this._transformContactToAddress(o),u=this._transformContactToAddress(a),h=null==a?void 0:a.emailAddress,p=(null==a?void 0:a.phoneNumber)||"";try{return yield this._paymentIntegrationService.updateBillingAddress(Object.assign(Object.assign({},l),{email:h,phone:p})),s&&(yield this._paymentIntegrationService.updateShippingAddress(u)),yield this._paymentIntegrationService.submitOrder({useStoreCredit:!1}),yield this._paymentIntegrationService.submitPayment(c),t.completePayment(ApplePaySession.STATUS_SUCCESS),this._onAuthorizeCallback()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),this._onError(e)}})}_transformContactToAddress(e){return{firstName:(null==e?void 0:e.givenName)||"",lastName:(null==e?void 0:e.familyName)||"",city:(null==e?void 0:e.locality)||"",company:"",address1:(null==e?void 0:e.addressLines)&&e.addressLines[0]||"",address2:(null==e?void 0:e.addressLines)&&e.addressLines[1]||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||"",phone:(null==e?void 0:e.phoneNumber)||"",stateOrProvince:(null==e?void 0:e.administrativeArea)||"",stateOrProvinceCode:(null==e?void 0:e.administrativeArea)||"",customFields:[]}}_getBraintreeDeviceData(){return Yi(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}function Ji(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}class Zi{create(e){return Ji(window),new ApplePaySession(1,e)}}class Qi{constructor(e){this.scriptLoader=e,this.sdkVersion="1.latest"}loadSdk(){return e=this,t=void 0,i=function*(){(function(e){return"ApplePaySDK"in e})(window)||(yield this.scriptLoader.loadScript(`https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`),Ji(window))},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const Xi=fi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new Ki(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]);class er extends Xn{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"}}const tr={body:{},headers:{},status:0};class nr extends Xn{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||tr;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}var ir,rr,or,ar,sr,dr,cr;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ir||(ir={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(rr||(rr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(or||(or={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(ar||(ar={})),function(e){e.pill="pill",e.rect="rect"}(sr||(sr={})),function(e){e.OXXO="oxxo"}(dr||(dr={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(cr||(cr={}));var lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ur{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.bigCommercePaymentsRequestSender=n,this.bigCommercePaymentsScriptLoader=i}loadPayPalSdk(e,t,n,i){return lr(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.bigCommercePaymentsScriptLoader.getPayPalSDK(a,o,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return lr(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ni(ei.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return lr(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.bigCommercePaymentsRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return lr(this,void 0,void 0,function*(){try{const{status:n}=yield this.bigCommercePaymentsRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ni(ei.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===Rt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return lr(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&ar[t]?t:void 0,height:this.getValidHeight(n),label:i&&or[i]?i:void 0,shape:r&&sr[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}const hr="This API endpoint is for internal use only and may change in the future";var pr;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(pr||(pr={}));const mr=pr,yr={"X-Checkout-SDK-Version":"1.904.1"};var gr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fr{constructor(e){this.requestSender=e}createOrder(e,t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return gr(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/bigcommerce_payments",{headers:n,body:t})).body})}getOrderStatus(e="bigcommerce_payments",t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var vr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _r{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i){return vr(this,void 0,void 0,function*(){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n);return this.loadPayPalSDK(r,i)})}loadPayPalSDK(e,t=!1){return vr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsPayPalSDK||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.bigCommercePaymentsPayPalSDK)throw new mi;return this.window.bigCommercePaymentsPayPalSDK})}getPayPalSdkScriptConfigOrThrow(e,t,n=!0){const{id:i,clientToken:r,initializationData:o}=e;if(!(null==o?void 0:o.clientId))throw new ni(ei.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isVenmoEnabled:u,isHostedCheckoutEnabled:h,isPayPalCreditAvailable:p,isDeveloperModeApplicable:m,availableAlternativePaymentMethods:y=[],enabledAlternativePaymentMethods:g=[],isGooglePayEnabled:f}=o,v=h||n,_="bigcommerce_payments_creditcards"===i,S=_?["card"]:[],I=_?[]:["card"],w=p?["credit","paylater"]:[],C=p?[]:["credit","paylater"],b=u?["venmo"]:[],P=u?[]:["venmo"],O=y.filter(e=>!g.includes(e)),E=f?["googlepay"]:[],A=n?["card-fields"]:[],T=this.filterFundingOptions([...I,...C,...P,...O]),k=this.filterFundingOptions([...S,...w,...b,...g]);return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":k.length>0?k:void 0,"disable-funding":T.length>0?T:void 0,commit:v,components:["buttons","hosted-fields","payment-fields","legal",...E,...A],currency:t,intent:a},m&&{"buyer-country":c}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"bigCommercePaymentsPayPalSDK"}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const Sr=e=>{const{getHost:t}=e.getState();return new ur(Ee(),e,new fr(n({host:t()})),new _r(a()))},Ir=40;var wr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return wr(this,void 0,void 0,function*(){const{bigcommerce_payments:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.bigcommerce_payments.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.bigcommerce_payments.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return wr(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return wr(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()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a}=t,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:c,paymentButtonStyles:l,isAppSwitchEnabled:u=!1}=d.initializationData||{},{checkoutTopButtonStyles:h}=l||{},p=Object.assign(Object.assign(Object.assign({},u&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)}),o&&{onClick:()=>o()}),m=Object.assign(Object.assign({},!u&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,a)}),y=Object.assign(Object.assign({fundingSource:s.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},h),{height:Ir}))},p),c&&m),g=s.Buttons(y);g.isEligible()?(null===(n=g.hasReturned)||void 0===n?void 0:n.call(g))&&u?null===(i=g.resume)||void 0===i||i.call(g):g.render(`#${r}`):this.bigCommercePaymentsIntegrationService.removeElement(r)}onHostedCheckoutApprove(e,t,n,i){return wr(this,void 0,void 0,function*(){if(!e.orderID)throw new ni(ei.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const br=fi(e=>new Cr(e,Sr(e)),[{id:"bigcommerce_payments"}]);var Pr,Or,Er,Ar,Tr,kr,Dr,Mr,zr,xr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Nr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n){return xr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsFastlaneSdk){const i=this.getPayPalFastlaneSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.bigCommercePaymentsFastlaneSdk)throw new mi}return this.window.bigCommercePaymentsFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i){return xr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsGooglePay||i){const i=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.bigCommercePaymentsGooglePay)throw new mi;return this.window.bigCommercePaymentsGooglePay})}getPayPalApmsSdk(e,t){return xr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsApms){const n=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(n),!this.window.bigCommercePaymentsApms)throw new mi}return this.window.bigCommercePaymentsApms})}getPayPalMessages(e,t){return xr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsMessages){const n=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(n)}if(!this.window.bigCommercePaymentsMessages)throw new mi;return this.window.bigCommercePaymentsMessages})}loadPayPalSdk({options:e,attributes:t}){return xr(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,attributionId:d}=r;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","three-domain-secure"],currency:t,intent:o},attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"bigCommercePaymentsFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":i}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n=!0){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||n;return{options:Object.assign({"client-id":a,"merchant-id":s,commit:h,components:["googlepay"],currency:t,intent:o},u&&{"buyer-country":d}),attributes:{"data-partner-attribution-id":c,"data-client-token":i,"data-namespace":"bigCommercePaymentsGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:i,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=n,u=this.filterFundingOptions(l),h=this.filterFundingOptions(c.filter(e=>!l.includes(e)));return{options:Object.assign({"client-id":r,"merchant-id":o,"enable-funding":u.length>0?u:void 0,"disable-funding":h.length>0?h:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:i},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"bigCommercePaymentsApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ni(ei.MissingPaymentMethod);const{clientId:i,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=n;return{options:Object.assign({"client-id":i,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"bigCommercePaymentsMessages","data-partner-attribution-id":o}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Rr(){return new Nr(o())}!function(e){e.CVV="cvv",e.PAN="pan"}(Pr||(Pr={}));class Fr{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,n=document.cookie;let i=null;const r=n.indexOf(t);if(r>-1){let e=n.indexOf(";",r);-1===e&&(e=n.length),i=decodeURIComponent(n.substring(r+t.length,e))}return i}static set(e,t,n={secure:!0}){let i=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:r,path:o,domain:a,secure:s}=n;if(r)i+=`; expires=${r.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),i+=`; expires=${e.toUTCString()}`}o&&(i+=`; path=${o}`),a&&(i+=`; domain=${a}`),s&&(i+="; secure"),document.cookie=i}static remove(e,t){Fr.set(e,"",Object.assign({expires:new Date(0)},t))}}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Or||(Or={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Er||(Er={})),function(e){e.Always="SCA_ALWAYS"}(Ar||(Ar={})),function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(Tr||(Tr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(kr||(kr={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Dr||(Dr={})),function(e){e.pill="pill",e.rect="rect"}(Mr||(Mr={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(zr||(zr={}));var Lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class jr{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return Lr(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.bigCommercePaymentsFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.bigCommercePaymentsFastlane=yield e.Fastlane({styles:n||t})}return this.window.bigCommercePaymentsFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.bigCommercePaymentsFastlane)throw new mi;return this.window.bigCommercePaymentsFastlane}lookupCustomerOrThrow(e){return Lr(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return Lr(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||zr.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function Br(){return new jr}function Ur(e){return"string"!=typeof e}function qr(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Ur),o=ue(e.input,Ur),a=ue(e.toggle,Ur),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Ur),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Ur),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,f,v,_,S,I,w,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.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===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.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===(p=null==t?void 0:t.input)||void 0===p?void 0:p.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===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(f=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===f?void 0:f.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(_=null===(v=null==t?void 0:t.text)||void 0===v?void 0:v.body)||void 0===_?void 0:_.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(S=null==t?void 0:t.text)||void 0===S?void 0:S.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var Vr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gr{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsSdk=t,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){var t;return Vr(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_fastlane:i}=e;if(!n)throw new vi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(o,r.currency.code,r.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return Vr(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId()})}signOut(e){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return Vr(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new vi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new vi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return Vr(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===zr.CANCELED;yield this.updateCustomerDataState(e,s),d?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return Vr(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return qr(r?i:{},null==t?void 0:t.styles)}}const Hr=fi(e=>new Gr(e,Rr(),Br()),[{id:"bigcommerce_payments_fastlane"},{id:"bigcommerce_payments_creditcards"}]);var Wr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $r{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return Wr(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_paylater.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_paylater.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC BigCommercePayments PayLater]: button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Wr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Wr(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()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d}=a.initializationData||{},{checkoutTopButtonStyles:c}=d||{},l=Object.assign({createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)},h=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let p=!1;h.forEach(e=>{if(!p){const t=Object.assign(Object.assign({fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},c),{height:Ir}))},l),s&&u),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),p=!0)}}),p||this.bigCommercePaymentsIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Wr(this,void 0,void 0,function*(){if(!e.orderID)throw new ni(ei.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Yr=fi(e=>new $r(e,Sr(e)),[{id:"bigcommerce_payments_paylater"}]);var Kr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return Kr(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_venmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_venmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC Payments Venmo]: Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Kr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Kr(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()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:Ir})),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.bigCommercePaymentsIntegrationService.removeElement(n)}}const Zr=fi(e=>new Jr(e,Sr(e)),[{id:"bigcommerce_payments_venmo"}]);class Qr extends Xn{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"}}class Xr extends nr{constructor(e){super(e,{message:"There is a problem processing your payment. Please try again later."}),this.name="PaymentMethodInvalidError",this.type="payment_method_invalid"}}var eo,to,no,io=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ro{constructor(e,t){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=window}initialize(e){var t;return io(this,void 0,void 0,function*(){const{methodId:n,bolt:i}=e,{onInit:r}=i||{};if(!n)throw new vi('Unable to proceed because "methodId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);if(!(null===(t=o.initializationData)||void 0===t?void 0:t.publishableKey))throw new ni(ei.MissingPaymentMethod);const{developerConfig:a,publishableKey:s}=o.initializationData;if(yield this.boltScriptLoader.loadBoltClient(s,o.config.testMode,a),r&&"function"==typeof r){const e=this.getCustomerEmail();r(yield this.hasBoltAccount(e),e)}})}deinitialize(){return Promise.resolve()}signIn(e,t){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){return io(this,void 0,void 0,function*(){const{continueWithCheckoutCallback:t=w,checkoutPaymentMethodExecuted:n,methodId:i}=e||{},r=this.getCustomerEmail();if(!i)throw new vi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof t)throw new vi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(r)return this.openBoltCheckoutModalOrThrow(r,i,t,n);t()})}openBoltCheckoutModalOrThrow(e,t,n,i){var r;return io(this,void 0,void 0,function*(){const o=this.getBoltClientOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethod(t);try{if(null===(r=null==a?void 0:a.initializationData)||void 0===r?void 0:r.embeddedOneClickEnabled){const t=yield this.hasBoltAccount(e);if(t){const t={close:()=>{n()}};yield o.openCheckout(e,t)}else n();"function"==typeof i&&i({hasBoltAccount:t})}else n()}catch(e){if(function(e){return"string"==typeof e.message&&"string"==typeof e.type&&("string"==typeof e.subtype||!e.subtype)&&e instanceof Error}(e)&&"MissingDataError"!==e.name&&"NotInitializedError"!==e.name)throw new Qr(e.message);throw e}})}getBoltClientOrThrow(){const e=this.boltHostWindow.BoltCheckout;if(!e)throw new ri(ti.PaymentNotInitialized);return e}hasBoltAccount(e){return io(this,void 0,void 0,function*(){const t=this.getBoltClientOrThrow();try{return yield t.hasBoltAccount(e)}catch(e){throw new Xr}})}getCustomerEmail(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress();return(null==t?void 0:t.email)||(null==n?void 0:n.email)||""}}!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(eo||(eo={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(to||(to={})),function(e){e.Pill="pill",e.Rect="rect"}(no||(no={}));var oo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ao{constructor(e,t=window){this.scriptLoader=e,this.boltHostWindow=t}loadBoltClient(e,t,n,i,r){return oo(this,void 0,void 0,function*(){if(this.boltHostWindow.BoltCheckout)return this.boltHostWindow.BoltCheckout;if(!e)throw new vi('Unable to initialize payment because "publishableKey" argument is not provided.');if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/connect-bigcommerce.js`,this.getScriptOptions("bolt-connect",e,i,r)),yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/track.js`,this.getScriptOptions("bolt-track",e)),!this.boltHostWindow.BoltCheckout)throw new mi;return this.boltHostWindow.BoltCheckout})}loadBoltEmbedded(e,t,n){return oo(this,void 0,void 0,function*(){if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/embed.js`,{async:!0,attributes:{id:"bolt-embedded"}}),!this.boltHostWindow.Bolt)throw new mi;return this.boltHostWindow.Bolt(e)})}getDomainURL(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case eo.StagingMode:return"connect-staging.bolt.com";case eo.DevelopmentMode:return`connect.${t.developerDomain}`}return"connect-sandbox.bolt.com"}getScriptOptions(e,t,n,i){return{async:!0,attributes:Object.assign(Object.assign({id:e,"data-publishable-key":t},n&&{"data-shopping-cart-id":n}),i&&{"data-storefront-api-token":i})}}}const so=fi(e=>new ro(e,new ao(a())),[{id:"bolt"}]);class co extends vi{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"}}class lo extends Xn{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"}}let uo=null;const ho=["buttons","messages"];var po,mo,yo,go,fo,vo;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(po||(po={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(mo||(mo={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(yo||(yo={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(go||(go={})),function(e){e.PILL="pill",e.RECT="rect"}(fo||(fo={})),function(e){e.CART="cart",e.HOME="homepage",e.PAYMENT="payment",e.PRODUCT="product"}(vo||(vo={}));var _o=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class So{constructor(e,t,n){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.overlay=n,this.dataCollectors={}}initialize(e,t){this.clientToken=e,this.threeDSecureOptions=t}getBraintreeFastlane(e,t,n){return _o(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(),i=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:i,deviceData:r,styles:n||a})}return this.braintreeHostWindow.braintreeFastlane})}getClient(){return _o(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,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["shouldSaveInstrument"]);const i=Ae();return this.getPaypal().then(e=>{var r;return i&&(null===(r=this.overlay)||void 0===r||r.show({onClick:()=>e.focusWindow()})),e.tokenize(Object.assign({enableShippingAddress:!0,flow:t?"vault":"checkout",useraction:"commit"},n))}).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,n){return _o(this,void 0,void 0,function*(){const i=yield this.getClient(),r=yield this.braintreeScriptLoader.loadPaypalCheckout(),o={client:i};return this.paypalCheckout=yield r.create(o,(i,r)=>{var o;if(i)return n(i);const a=Object.assign(Object.assign({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:ho.toString(),intent:e.intent,commit:null===(o=e.commit)||void 0===o||o});this.braintreeHostWindow.paypal?t(r):function(e,t){return uo||(uo=new Promise((n,i)=>{e.loadPayPalSDK(t,t=>{t?(uo=null,i(t)):n(e)})})),uo}(r,a).then(()=>t(r))}),this.paypalCheckout})}getDataCollector(e){return _o(this,void 0,void 0,function*(){const t=(null==e?void 0:e.paypal)?"paypal":"default";let n=this.dataCollectors[t];if(!n){try{const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadDataCollector(),r=Object.assign({client:t,kount:!0},e);n=yield i.create(r)}catch(e){if(!Ri(e)||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==e.code)throw e;n={deviceData:void 0,teardown:()=>Promise.resolve()}}this.dataCollectors[t]=n}return n})}getBraintreeEnv(e=!1){return e?Fi.Sandbox:Fi.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:n,shippingAddress:i}=e,r=(null==i?void 0:i.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:n,address_line_1:null==i?void 0:i.line1,address_line_2:null==i?void 0:i.line2,city:null==i?void 0:i.city,state:null==i?void 0:i.state,country_code:null==i?void 0:i.countryCode,postal_code:null==i?void 0:i.postalCode}}mapToLegacyBillingAddress(e){const{billingAddress:t,email:n,firstName:i,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:n,first_name:i,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 _o(this,void 0,void 0,function*(){const{deviceData:t}=yield this.getDataCollector({riskCorrelationId:e});return t})}teardown(){return _o(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 _o(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 _o(this,void 0,void 0,function*(){if(!this.venmoCheckout){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadVenmoCheckout(),i=Object.assign({client:t,allowDesktop:!0,paymentMethodUsage:"multi_use"},e||{});this.venmoCheckout=yield new Promise((e,t)=>{n.create(i,(n,i)=>n?t(n):i.isBrowserSupported()?void e(i):t(new Ai))})}return this.venmoCheckout})}verifyCard(e,t,n){return _o(this,void 0,void 0,function*(){const i=yield this.tokenizeCard(e,t);return this.challenge3DSVerification(i,n)})}tokenizeCard(e,t){return _o(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 co(["payment.paymentData"]);const i=this.getErrorsRequiredFields(n);if(!$(i))throw new lo(i);const r=this.mapToCreditCard(n,t),o=yield this.getClient(),{creditCards:a}=yield o.request(r);return{nonce:a[0].nonce,bin:a[0].details.bin}})}challenge3DSVerification(e,t){return _o(this,void 0,void 0,function*(){const n=yield this.get3DS();return this.present3DSChallenge(n,t,e)})}teardownModule(e){return e?e.teardown():Promise.resolve()}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ti.PaymentNotInitialized);return this.clientToken}getErrorsRequiredFields(e){const{ccNumber:t,ccExpiry:n}=e,i={};return t||(i.ccNumber=[{message:"Credit card number is required",type:"required"}]),n||(i.ccExpiry=[{message:"Expiration date is required",type:"required"}]),i}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,n){const{nonce:i,bin:r}=n;if(!this.threeDSecureOptions||!i)throw new ri(ti.PaymentNotInitialized);const{addFrame:o,removeFrame:a,challengeRequested:s=!0,additionalInformation:d}=this.threeDSecureOptions,c=()=>_o(this,void 0,void 0,function*(){const t=yield e.cancelVerifyCard();return u.cancel(new Wi),t}),l=t.toFixed(2),u=new An(e.verifyCard({addFrame:(e,t)=>{o&&o(e,t,c)},amount:Number(l),bin:r,challengeRequested:s,nonce:i,removeFrame:a,onLookupComplete:(e,t)=>{t()},collectDeviceData:!0,additionalInformation:d}));return u.promise}}var Io=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wo{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return Io(this,void 0,void 0,function*(){const{braintreepaypal:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ni(ei.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ni(ei.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),u)},e=>this.handleError(e,i,r))})}deinitialize(){return Io(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return Io(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Io(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,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow,d=null==s?void 0:s.FUNDING.PAYPAL;if(s&&d){const c=s.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(i),fundingSource:d,style:Object.assign(Object.assign({},r),{height:Ir}),createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});c.isEligible()&&c.render(`#${o}`)}else this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return Io(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(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!1,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return Io(this,void 0,void 0,function*(){try{const{deviceData:i}=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:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Co=fi(e=>{const t=window,n=new Ei(e),i=new So(new Hi(a(),t,n),t);return new wo(e,Ee(),i,t)},[{id:"braintreepaypal"}]);var bo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Po{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return bo(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.braintreepaypalcredit.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ni(ei.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ni(ei.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),Object.assign(Object.assign({},u),{height:Ir}))},e=>this.handleError(e,i,r))})}deinitialize(){return bo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return bo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return bo(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,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow;let d=!1;s&&[s.FUNDING.PAYLATER,s.FUNDING.CREDIT].forEach(c=>{if(!d){const l=s.Buttons({env:i?"sandbox":"production",fundingSource:c,style:r,createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});l.isEligible()&&(l.render(`#${o}`),d=!0)}}),s&&d||this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return bo(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(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!0,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return bo(this,void 0,void 0,function*(){try{const{deviceData:i}=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:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Oo=fi(e=>{const t=window,n=new Ei(e),i=new So(new Hi(a(),t,n),t);return new Po(e,Ee(),i,t)},[{id:"braintreepaypalcredit"}]);function Eo(e){return"string"!=typeof e}function Ao(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Eo),o=ue(e.input,Eo),a=ue(e.toggle,Eo),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Eo),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Eo),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,f,v,_,S,I,w,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.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===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.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===(p=null==t?void 0:t.input)||void 0===p?void 0:p.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===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(f=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===f?void 0:f.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(_=null===(v=null==t?void 0:t.text)||void 0===v?void 0:v.body)||void 0===_?void 0:_.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(S=null==t?void 0:t.text)||void 0===S?void 0:S.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var To=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ko{constructor(e,t){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.isAcceleratedCheckoutEnabled=!1}initialize({methodId:e,braintreefastlane:t}){var n;return To(this,void 0,void 0,function*(){if(!e)throw new vi('Unable to proceed because "methodId" argument is not provided.');const i=yield this.getValidPaymentMethodOrThrow(e),{isAcceleratedCheckoutEnabled:r,isFastlaneStylingEnabled:o}=i.initializationData||{},a=o?null===(n=i.initializationData)||void 0===n?void 0:n.fastlaneStyles:void 0;this.isAcceleratedCheckoutEnabled=!!r;try{if(this.isAcceleratedCheckoutEnabled){const e=Ao(a,null==t?void 0:t.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(i.id,e)}}catch(e){}return Promise.resolve()})}deinitialize(){return To(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return To(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n}=e||{};if("function"!=typeof n)throw new vi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');const i=this.paymentIntegrationService.getState().getCustomerOrThrow();if(this.isAcceleratedCheckoutEnabled&&i.isGuest){const e=yield this.shouldRunAuthenticationFlow();t&&"function"==typeof t&&t(),e&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(void 0,!0))}n()})}shouldRunAuthenticationFlow(){var e;return To(this,void 0,void 0,function*(){const t="braintreeacceleratedcheckout";try{yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t);return(null===(e=n.initializationData)||void 0===e?void 0:e.shouldRunAcceleratedCheckout)||!1}catch(e){return!1}})}getValidPaymentMethodOrThrow(e){return To(this,void 0,void 0,function*(){let t=e;try{yield this.paymentIntegrationService.loadPaymentMethod(t)}catch(n){t="braintree"===e?"braintreeacceleratedcheckout":"braintree",yield this.paymentIntegrationService.loadPaymentMethod(t)}return this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)})}}var Do=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mo{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}getDeviceSessionId(){return Do(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 Do(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getCart(),{clientToken:r,config:o}=n.getPaymentMethodOrThrow(e);if(!r)throw new ni(ei.MissingPaymentMethod);this.methodId=e,this.braintreeIntegrationService.initialize(r),this.braintreeFastlane=yield this.braintreeIntegrationService.getBraintreeFastlane(null==i?void 0:i.id,o.testMode,t)})}getBraintreeFastlaneOrThrow(){if(!this.braintreeFastlane)throw new mi;return this.braintreeFastlane}getBraintreeFastlaneComponentOrThrow(){return this.getBraintreeFastlaneOrThrow().FastlaneCardComponent}runPayPalAuthenticationFlowOrThrow(e,t){var n;return Do(this,void 0,void 0,function*(){try{const i=this.getMethodIdOrThrow(),r=this.getBraintreeFastlaneOrThrow(),{lookupCustomerByEmail:o,triggerAuthenticationFlow:a}=r.identity,s=this.paymentIntegrationService.getState(),d=s.getCartOrThrow(),c=s.getCustomer(),l=s.getBillingAddress(),{isFastlaneShippingOptionAutoSelectEnabled:u}=s.getPaymentMethodOrThrow(i).initializationData||{},h=e||(null==c?void 0:c.email)||(null==l?void 0:l.email)||"",{customerContextId:p}=yield o(h);if(!p)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:Mi.UNRECOGNIZED,addresses:[],instruments:[]}),void this.saveSessionIdToCookies(d.id);const{authenticationState:m,profileData:y}=yield a(p),g=(null===(n=null==y?void 0:y.shippingAddress)||void 0===n?void 0:n.phoneNumber)||"";if(m===Mi.CANCELED)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:[],instruments:[]}),void this.removeSessionIdFromCookies();const f=this.mapPayPalToBcAddress([y.shippingAddress],[g])||[],v=this.getPayPalBillingAddresses(y),_=v?this.mapPayPalToBcAddress([v],[g]):[],S=y.card?this.mapPayPalToBcInstrument(i,[y.card]):[],I=this.mergeShippingAndBillingAddresses(f,_);if(this.saveSessionIdToCookies(d.id),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:I,instruments:S}),_.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateBillingAddress(_[0])),_.length>0&&d.lineItems.digitalItems.length>0&&0===d.lineItems.physicalItems.length){const{firstName:e,lastName:t}=I[0],n=Object.assign(Object.assign({},_[0]),{firstName:e,lastName:t});yield this.paymentIntegrationService.updateBillingAddress(n)}f.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateShippingAddress(f[0]),t&&u&&(yield this.setShippingOption()))}catch(e){}})}getSessionIdFromCookies(){return Fr.get("bc-fastlane-sessionId")||""}saveSessionIdToCookies(e){const t=new Date;t.setDate(t.getDate()+14),Fr.set("bc-fastlane-sessionId",e,{expires:t,secure:!0})}removeSessionIdFromCookies(){Fr.remove("bc-fastlane-sessionId")}mapPayPalToBcInstrument(e,t){if(t)return t.map(t=>{const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a,binDetails:s}=i.card,[d,c]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:c,expiryYear:d,iin:(null==s?void 0:s.bin)||"",last4:a,method:e,provider:e,trustedShippingAddress:!1,type:"card",untrustedShippingCardVerificationMode:Pr.PAN}})}mapPayPalToBcAddress(e,t){if(!e)return[];const n=this.paymentIntegrationService.getState().getCountries()||[],i=e=>{const t=n.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:i(e.countryCodeAlpha2),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:t&&t[0]||"",customFields:[]}))}getPayPalBillingAddresses(e){const{card:t,name:n}=e||{};if(!t)return;const{firstName:i,lastName:r}=t.paymentSource.card.billingAddress,{firstName:o,lastName:a}=n||{},{shippingAddress:s}=e||{},d=Object.assign(Object.assign({},t.paymentSource.card.billingAddress),{firstName:i||o,lastName:r||a});return s&&Y(this.normalizeAddress(d),this.normalizeAddress(s))?s:d}normalizeAddress(e){return le(e,["id"])}mergeShippingAndBillingAddresses(e,t){const n=t.filter(t=>!e.some(e=>Y(this.normalizeAddress(e),this.normalizeAddress(t))));return[...e,...n]}getMethodIdOrThrow(){if(!this.methodId)throw new vi('Unable to proceed because "methodId" argument is not provided.');return this.methodId}setShippingOption(){var e;return Do(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getConsignments()||[],n=(null===(e=t[0])||void 0===e?void 0:e.availableShippingOptions)||[],i=n.find(e=>e.isRecommended);if(i||n.length){const e=i||n[0];yield this.paymentIntegrationService.selectShippingOption(e.id)}})}}const zo=fi(e=>{const t=window,n=new Ei(e),i=new So(new Hi(a(),t,n),t),r=new Mo(e,i);return new ko(e,r)},[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);var xo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class No{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n,this.buttonClassName="visa-checkout-wrapper",this.onError=ce}initialize(e){return xo(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!n)throw new vi('Unable to proceed because "methodId" argument is not provided.');if(!t)throw new vi('Unable to proceed because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getCheckoutOrThrow(),{clientToken:o,config:a}=i.getPaymentMethodOrThrow(n),s=i.getStoreConfigOrThrow();if(!o)throw new ni(ei.MissingPaymentMethod);this.braintreeSdk.initialize(o);const d=yield this.braintreeSdk.getBraintreeVisaCheckout(),c=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),{container:l,onError:u}=t;this.onError=u||ce;const h=d.createInitOptions({paymentRequest:{currencyCode:s.currency.code,subtotal:String(r.subtotal)},settings:{locale:s.storeProfile.storeLanguage,shipping:{collectShipping:!0}}}),p=this.createSignInButton(l,this.buttonClassName);yield c.init(h),c.on("payment.success",e=>this.tokenizePayment(d,e).then(()=>this.paymentIntegrationService.loadCheckout()).catch(e=>this.handleError(e))),c.on("payment.error",(e,t)=>this.handleError(t)),p.style.visibility="visible"})}deinitialize(){return xo(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}signIn(){throw new _i('In order to sign in via VisaCheckout, the shopper must click on "Visa Checkout" button.')}signOut(e){return xo(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 xo(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{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,i)),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 n=document.querySelector(`#${e}`);if(!n)throw new Error("Unable to proceed because the provided container ID is not valid.");return this.insertVisaCheckoutButton(n,t)}insertVisaCheckoutButton(e,t){const n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.visibility="hidden",n.style.width="max-content",n.className=t,n.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(n),n}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Ro=fi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new No(e,Ee(),i)},[{id:"braintreevisacheckout"}]);class Fo{constructor(e){if(!e)throw new Error("Currency settings missing");const{decimalPlaces:t,symbolLocation:n,symbol:i,thousandsSeparator:r,decimalSeparator:o}=e;if("string"!=typeof n||"string"!=typeof i||"string"!=typeof r||"string"!=typeof o||"string"!=typeof t)throw new vi("Invalid currency settings provided");this._decimalPlaces=parseInt(t,10),this._symbolLocation=n,this._symbol=i,this._thousandsSeparator=r,this._decimalSeparator=o}format(e){if("number"!=typeof e)throw new vi("Invalid amount provided");const t=this._formatNumber(e),n=this._formatCurrency(t);return e<0?`-${n}`:n}_formatNumber(e){const t=Math.abs(e),[n,i=""]=this._toFixed(t,this._decimalPlaces).split("."),r=n.replace(/\B(?=(\d{3})+(?!\d))/g,this._thousandsSeparator);return this._decimalPlaces<1?r:[r,i].join(this._decimalSeparator)}_formatCurrency(e){return"left"===this._symbolLocation.toLowerCase()?`${this._symbol}${e}`:`${e}${this._symbol}`}_toFixed(e,t){return(+`${Math.round(+`${e}e${t}`)}e${-t}`).toFixed(t)}}let Lo=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};Lo=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],Lo);const jo=Lo,Bo=(e,t)=>!!e&&(!!e.lineItems.physicalItems.some(e=>e.isShippingRequired)||!(!t||!e.lineItems.customItems)&&e.lineItems.customItems.length>0);function Uo(){if("undefined"==typeof window)return!1;if(function(e){return"ReactNativeWebView"in e}(window))return!0;const e=navigator.userAgent||navigator.vendor||(function(e){return"opera"in e}(window)?window.opera:""),t=/android.+; wv/i.test(e),n=/iPhone|iPod|iPad/i.test(e)&&/AppleWebKit/i.test(e)&&!/Safari/i.test(e);return t||n}var qo,Vo,Go,Ho,Wo,$o,Yo,Ko,Jo;function Zo(e){return e in $o}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(qo||(qo={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Vo||(Vo={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Go||(Go={})),function(e){e.pill="pill",e.rect="rect"}(Ho||(Ho={})),function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Wo||(Wo={})),function(e){e.AMEX="AMEX",e.DISCOVER="DISCOVER",e.INTERAC="INTERAC",e.JCB="JCB",e.MC="MASTERCARD",e.VISA="VISA"}($o||($o={})),function(e){e.OFFER="OFFER",e.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.SHIPPING_OPTION="SHIPPING_OPTION"}(Yo||(Yo={})),function(e){e.OFFER_INVALID="OFFER_INVALID",e.PAYMENT_DATA_INVALID="PAYMENT_DATA_INVALID",e.SHIPPING_ADDRESS_INVALID="SHIPPING_ADDRESS_INVALID",e.SHIPPING_ADDRESS_UNSERVICEABLE="SHIPPING_ADDRESS_UNSERVICEABLE",e.SHIPPING_OPTION_INVALID="SHIPPING_OPTION_INVALID",e.OTHER_ERROR="OTHER_ERROR"}(Ko||(Ko={})),function(e){e.INITIALIZE="INITIALIZE",e.SHIPPING_OPTION="SHIPPING_OPTION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.OFFER="OFFER"}(Jo||(Jo={}));var Qo,Xo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ea{constructor(e,t){this._gatewayIdentifier=e,this._paymentIntegrationService=t,this._isBuyNowFlow=!1,this._shouldRequestShipping=!0,this._isWebViewExperimentOn=null}mapToShippingAddressRequestBody({shippingAddress:e}){if(!e)return;const{company:t="",phone:n=""}=this._paymentIntegrationService.getState().getShippingAddress()||{};return this._mapToAddressRequestBody(e,t,n)}mapToBillingAddressRequestBody(e){const{billingAddress:t}=e.paymentMethodData.info;if(!t)return;const{company:n="",phone:i="",email:r,customFields:o=[]}=this._paymentIntegrationService.getState().getBillingAddress()||{};return Object.assign(Object.assign({},this._mapToAddressRequestBody(t,n,i,o)),{email:r||e.email})}mapToExternalCheckoutData(e){var t;const{paymentMethodData:{tokenizationData:{token:n},info:{cardNetwork:i,cardDetails:r}}}=e;if(!n)throw new ni(ei.MissingPaymentToken);return Promise.resolve(Object.assign({nonce:n,card_information:{type:i,number:r}},this._isBuyNowFlow&&{cart_id:null===(t=this._paymentIntegrationService.getState().getCart())||void 0===t?void 0:t.id}))}getRequiredData(){var e;return Xo(this,void 0,void 0,function*(){const t={emailRequired:!0};if(!this._isShippingAddressRequired())return t;const n=yield this._paymentIntegrationService.loadShippingCountries(),i=null===(e=n.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code);return Object.assign(Object.assign({},t),{shippingAddressRequired:!0,shippingAddressParameters:Object.assign({phoneNumberRequired:!0},i&&{allowedCountryCodes:i}),shippingOptionRequired:!0})})}getCallbackIntents(){return this._isShippingAddressRequired()?[Yo.OFFER,Yo.SHIPPING_ADDRESS,Yo.SHIPPING_OPTION]:[Yo.OFFER]}getCallbackTriggers(){return{availableTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS,Jo.SHIPPING_OPTION,Jo.OFFER],initializationTrigger:[Jo.INITIALIZE],addressChangeTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS],shippingOptionsChangeTriggers:[Jo.SHIPPING_OPTION],offerChangeTriggers:[Jo.OFFER]}}getNonce(e){var t;const n=null===(t=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.nonce;if(!n)throw new ni(ei.MissingPaymentToken);return Promise.resolve(n)}extraPaymentData(){return Promise.resolve(void 0)}getMerchantInfo(){const{googleMerchantName:e,googleMerchantId:t,platformToken:n}=this.getGooglePayInitializationData();return{merchantName:e,merchantId:t,authJwt:n}}getTransactionInfo(){let e;const{getCartOrThrow:t}=this._paymentIntegrationService.getState();e=this._isBuyNowFlow?this._getCurrencyCodeOrThrow():t().currency.code;const n=this.getGooglePayInitializationData().storeCountry;if(this.isWebViewWithRestrictions()){const t=this.getTotalPrice();return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPrice:t,totalPriceStatus:Wo.ESTIMATED})}return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPriceStatus:Wo.ESTIMATED,totalPrice:"0"})}isWebViewWithRestrictions(){return null!==this._isWebViewExperimentOn?this._isWebViewExperimentOn&&Uo():Uo()}setIsWebViewExperimentOn(e){this._isWebViewExperimentOn=e}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData().gatewayMerchantId;if(!e)throw new vi("Unable to proceed, gatewayMerchantId is missing.");return{gateway:this._gatewayIdentifier,gatewayMerchantId:e}}getCardParameters(){return{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.getPaymentMethod().supportedCards.filter(Zo).map(e=>$o[e]),billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!0}}}initialize(e,t,n){return this._getPaymentMethodFn=e,this._isBuyNowFlow=Boolean(t),this._currencyCode=n,this._isBuyNowFlow&&this._getCurrencyCodeOrThrow(),Promise.resolve()}handleShippingAddressChange(e){var t,n,i,r;return Xo(this,void 0,void 0,function*(){e&&(e.name=e.name||"",e.address1=e.address1||"");const o=this.mapToShippingAddressRequestBody({shippingAddress:e});o&&(yield this._paymentIntegrationService.updateShippingAddress(o));const a=this._paymentIntegrationService.getState(),s=a.getConsignments();if(!(null==s?void 0:s[0]))return;const d=s[0],c=a.getStoreConfigOrThrow();this._currencyService||(this._currencyService=new jo(c));const l=(d.availableShippingOptions||[]).map(this._getGooglePayShippingOption.bind(this)),u=null===(t=d.availableShippingOptions)||void 0===t?void 0:t.find(e=>e.isRecommended);if(l.length){const e=(null===(n=d.selectedShippingOption)||void 0===n?void 0:n.id)||(null==u?void 0:u.id)||(null===(i=l[0])||void 0===i?void 0:i.id);return!(null===(r=d.selectedShippingOption)||void 0===r?void 0:r.id)&&l[0]&&(yield this.handleShippingOptionChange((null==u?void 0:u.id)||l[0].id)),{defaultSelectedOptionId:e,shippingOptions:l}}})}handleShippingOptionChange(e){return Xo(this,void 0,void 0,function*(){if("shipping_option_unselected"!==e)return this._paymentIntegrationService.selectShippingOption(e)})}getTotalPrice(){const{getCheckoutOrThrow:e,getCartOrThrow:t,getStoreConfigOrThrow:n}=this._paymentIntegrationService.getState(),{decimalPlaces:i}=t().currency,r=Ci(n().checkoutSettings.features,"PI-5075.google_pay_round_total_price_to_max_2_decimal_places")?Math.min(i,2):i;return ge(e().outstandingBalance,r).toFixed(r)}handleCoupons(e){return Xo(this,void 0,void 0,function*(){const{redemptionCodes:t=[]}=e,{offers:n}=this.getAppliedCoupons()||{};let i;return yield t.reduce((e,t)=>Xo(this,void 0,void 0,function*(){if(yield e,(n||[]).some(({redemptionCode:e})=>e===t))return;const r=yield this.applyCoupon(t);r&&(i=r)}),Promise.resolve()),yield(n||[]).reduce((e,n)=>Xo(this,void 0,void 0,function*(){yield e,t.includes(n.redemptionCode)||(yield this._paymentIntegrationService.removeCoupon(n.redemptionCode))}),Promise.resolve()),{newOfferInfo:this.getAppliedCoupons(),error:i}})}getAppliedCoupons(){const e=this._paymentIntegrationService.getState(),{coupons:t}=e.getCheckout()||{};return{offers:(t||[]).map(e=>{const{displayName:t,code:n}=e;return{redemptionCode:n,description:t}})}}applyCoupon(e){return Xo(this,void 0,void 0,function*(){let t;try{yield this._paymentIntegrationService.applyCoupon(e)}catch(e){return e instanceof Error&&(t={reason:Ko.OFFER_INVALID,message:e.message,intent:Jo.OFFER}),t}})}setShouldRequestShipping(e){this._shouldRequestShipping=e}getGooglePayInitializationData(){return ii(this.getPaymentMethod().initializationData,()=>new vi("Missing initialization data."))}getPaymentMethod(){return ii(this._getPaymentMethodFn,()=>new ri(ti.PaymentNotInitialized))()}getGatewayIdentifier(){return this._gatewayIdentifier}setGatewayIdentifier(e){this._gatewayIdentifier=e||this.getGatewayIdentifier()}_isShippingAddressRequired(){const{getCartOrThrow:e,getStoreConfigOrThrow:t,getShippingAddress:n}=this._paymentIntegrationService.getState(),i=t();let r;return r=Ci(i.checkoutSettings.features,"PI-4290.google_pay_require_shipping_address")?this._shouldRequestShipping:void 0===n(),r&&Bo(e(),i)}_mapToAddressRequestBody(e,t,n,i){const{name:r,address1:o,address2:a,address3:s,locality:d,administrativeArea:c,countryCode:l,postalCode:u,phoneNumber:h}=e,[p,m]=this._getFirstAndLastName(r);return{firstName:p,lastName:m,company:t,address1:o,address2:`${a} ${s}`.trim(),city:d||c,stateOrProvince:c,stateOrProvinceCode:c,countryCode:l,postalCode:u,phone:h||n,customFields:i||[]}}_getFirstAndLastName(e){const t=e.split(" ");return 1===t.length?[e,""]:[t.slice(0,-1).join(" "),t[t.length-1]]}_getCurrencyCodeOrThrow(){return ii(this._currencyCode,()=>new vi('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}_getGooglePayShippingOption({id:e,cost:t,description:n,additionalDescription:i}){var r;return{id:e,label:`${(null===(r=this._currencyService)||void 0===r?void 0:r.toCustomerCurrency(t))||t} ${n}`,description:i}}}function ta(e){return"object"==typeof e&&null!==e&&"statusCode"in e}function na(e){return Object.values(Qo).includes(e)}!function(e){e.ADYEN_V2="googlepayadyenv2",e.ADYEN_V3="googlepayadyenv3",e.AUTHORIZE_NET="googlepayauthorizenet",e.BNZ="googlepaybnz",e.BRAINTREE="googlepaybraintree",e.PAYPAL_COMMERCE="googlepaypaypalcommerce",e.BIGCOMMERCE_PAYMENTS="googlepay_bigcommerce_payments",e.CHECKOUT_COM="googlepaycheckoutcom",e.CYBERSOURCE_V2="googlepaycybersourcev2",e.ORBITAL="googlepayorbital",e.STRIPE="googlepaystripe",e.STRIPE_UPE="googlepaystripeupe",e.STRIPE_OCS="googlepaystripeocs",e.WORLDPAY_ACCESS="googlepayworldpayaccess",e.TD_ONLINE_MART="googlepaytdonlinemart"}(Qo||(Qo={}));var ia=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ra{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,n;return ia(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new vi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!i)throw new vi("Unable to proceed without valid options.");let r,o=this._paymentIntegrationService.getState();try{r=o.getPaymentMethodOrThrow(this._getMethodId())}catch(e){o=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),r=o.getPaymentMethodOrThrow(this._getMethodId())}try{this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(t=r.initializationData)||void 0===t?void 0:t.isWebViewExperimentOn)),yield this._googlePayPaymentProcessor.initialize(()=>r,this._getGooglePayClientOptions(null===(n=r.initializationData)||void 0===n?void 0:n.storeCountry))}catch(e){return}this._addPaymentButton(i)})}signIn(){return Promise.reject(new _i('In order to sign in via Google Pay, the shopper must click on "Google Pay" button.'))}signOut(){var e;return ia(this,void 0,void 0,function*(){const t=null===(e=this._paymentIntegrationService.getState().getPaymentId())||void 0===e?void 0:e.providerId;t&&(yield this._googlePayPaymentProcessor.signOut(t))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,shippingAddress:n,shippingOptionData:i,offerData:r})=>ia(this,void 0,void 0,function*(){const{availableTriggers:o,addressChangeTriggers:a,shippingOptionsChangeTriggers:s,offerChangeTriggers:d}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!o.includes(t))return;const c=a.includes(t)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(n):void 0;s.includes(t)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(i.id));const{newOfferInfo:l,error:u}=d.includes(t)?yield this._googlePayPaymentProcessor.handleCoupons(r):{},h=u;yield this._paymentIntegrationService.loadCheckout();const p=this._googlePayPaymentProcessor.getTotalPrice(),{code:m}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:m,totalPriceStatus:Wo.FINAL,totalPrice:p})},c&&{newShippingOptionParameters:c}),l&&{newOfferInfo:l}),h&&{error:h})})}}}_addPaymentButton({container:e,buttonColor:t,buttonType:n,onClick:i,onError:r}){var o;this._paymentButton=null!==(o=this._paymentButton)&&void 0!==o?o:this._googlePayPaymentProcessor.addPaymentButton(e,{buttonColor:null!=t?t:"default",buttonType:null!=n?n:"plain",onClick:this._handleClick(r,i)})}_handleClick(e,t){return n=>ia(this,void 0,void 0,function*(){n.preventDefault(),t&&"function"==typeof t&&t();try{yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let n=t;if(ta(t)){if("CANCELED"===t.statusCode)throw new Wi;n=new Qr(JSON.stringify(t))}throw null==e||e(new Qr("An error occurred while requesting your Google Pay payment details.")),n}})}_interactWithPaymentSheet(){return ia(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e),n=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(e),i="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;t&&(yield this._paymentIntegrationService.updateBillingAddress(t)),n&&(yield this._paymentIntegrationService.updateShippingAddress(n)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodId(),e,i)})}_getMethodId(){return ii(this._methodId,()=>new ri(ti.PaymentNotInitialized))}}var oa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class aa{constructor(e,t,n,i){this._scriptLoader=e,this._gateway=t,this._requestSender=n,this._formPoster=i,this._baseRequest={apiVersion:2,apiVersionMinor:0}}initialize(e,t,n,i){return oa(this,void 0,void 0,function*(){this._paymentsClient=yield this._scriptLoader.getGooglePaymentsClient(e().config.testMode,t),yield this._gateway.initialize(e,n,i),this._buildButtonPayloads()})}initializeWidget(){return oa(this,void 0,void 0,function*(){yield this._buildWidgetPayloads(),yield this._determineReadinessToPay(),this._prefetchGooglePaymentData()})}getNonce(e){return this._gateway.getNonce(e)}extraPaymentData(){return oa(this,void 0,void 0,function*(){return this._gateway.extraPaymentData()})}addPaymentButton(e,t){const n=document.querySelector(`#${e}`);if(!n)return;const i=this._getPaymentsClient().createButton(Object.assign(Object.assign({},t),{allowedPaymentMethods:[this._getBaseCardPaymentMethod()]}));return n.appendChild(i)}showPaymentSheet(){return oa(this,void 0,void 0,function*(){const e=this._getPaymentDataRequest();return this._getPaymentsClient().loadPaymentData(e)})}setExternalCheckoutXhr(e,t){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t)})}setExternalCheckoutForm(e,t,n){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t,!0,n)})}mapToBillingAddressRequestBody(e){return this._gateway.mapToBillingAddressRequestBody(e)}mapToShippingAddressRequestBody(e){return this._gateway.mapToShippingAddressRequestBody(e)}processAdditionalAction(e,t){return"processAdditionalAction"in this._gateway?this._gateway.processAdditionalAction(e,t):Promise.reject(e)}signOut(e){return oa(this,void 0,void 0,function*(){yield this._requestSender.get(`/remote-checkout/${e}/signout`)})}getCallbackTriggers(){return this._gateway.getCallbackTriggers()}setShouldRequestShipping(e){return this._gateway.setShouldRequestShipping(e)}handleShippingAddressChange(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleShippingAddressChange(e)})}handleShippingOptionChange(e){return oa(this,void 0,void 0,function*(){yield this._gateway.handleShippingOptionChange(e)})}handleCoupons(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleCoupons(e)})}getTotalPrice(){return this._gateway.getTotalPrice()}_setExternalCheckout(e,t,n=!1,i){return oa(this,void 0,void 0,function*(){const r="/checkout.php",o=Object.assign({action:"set_external_checkout",provider:e},yield this._gateway.mapToExternalCheckoutData(t));if(n)return new Promise(e=>{this._formPoster.postForm(i?`${i}/checkout`:r,Object.assign(Object.assign({},o),{card_information:JSON.stringify(o.card_information)}),e)});yield this._requestSender.post(r,{headers:Object.assign({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},yr),body:o})})}isWebViewWithRestrictions(){return this._gateway.isWebViewWithRestrictions()}setIsWebViewExperimentOn(e){return this._gateway.setIsWebViewExperimentOn(e)}_prefetchGooglePaymentData(){const e=this._getPaymentDataRequest();e.transactionInfo=this._gateway.getTransactionInfo(),this._getPaymentsClient().prefetchPaymentData(e)}_determineReadinessToPay(){return oa(this,void 0,void 0,function*(){try{const{result:e}=yield this._getPaymentsClient().isReadyToPay(this._getIsReadyToPayRequest());if(!1===e)throw new Qr("Google Pay is not supported by the current device and browser, please try another payment method.")}catch(e){if(e instanceof Qr)throw e;throw new Qr}})}_buildButtonPayloads(){this._baseCardPaymentMethod={type:"CARD",parameters:this._gateway.getCardParameters()}}_buildWidgetPayloads(){return oa(this,void 0,void 0,function*(){const e=this._getBaseCardPaymentMethod();this._cardPaymentMethod=Object.assign(Object.assign({},e),{tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:yield this._gateway.getPaymentGatewayParameters()}});const t=this._gateway.isWebViewWithRestrictions()?{shippingOptionRequired:!1}:{callbackIntents:this._gateway.getCallbackIntents(),offerInfo:this._gateway.getAppliedCoupons()};this._paymentDataRequest=Object.assign(Object.assign(Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[this._cardPaymentMethod],transactionInfo:this._gateway.getTransactionInfo(),merchantInfo:this._gateway.getMerchantInfo()}),yield this._gateway.getRequiredData()),t),this._isReadyToPayRequest=Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[e]})})}_getBaseCardPaymentMethod(){return this._getOrThrow(this._baseCardPaymentMethod)}_getPaymentDataRequest(){return this._getOrThrow(this._paymentDataRequest)}_getIsReadyToPayRequest(){return this._getOrThrow(this._isReadyToPayRequest)}_getPaymentsClient(){return this._getOrThrow(this._paymentsClient)}_getOrThrow(e){return ii(e,()=>new ri(ti.PaymentNotInitialized))}}class sa{constructor(e){this._scriptLoader=e,this._window=window}getGooglePaymentsClient(e=!1,t){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript("https://pay.google.com/gp/p/js/pay.js"),!this._window.google)throw new mi;return void 0===this._paymentsClient&&(this._paymentsClient=new this._window.google.payments.api.PaymentsClient(Object.assign({environment:e?"TEST":"PRODUCTION"},null!=t?t:{}))),this._paymentsClient},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function da(){return new sa(a())}const ca=fi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),la=fi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]);class ua extends ea{constructor(e){super("authorizenet",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return function(e){if(!function(e){return"paymentGatewayId"in e}(e))throw new ni(ei.MissingPaymentMethod)}(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.paymentGatewayId}}}const ha=fi(e=>new ra(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),pa=e=>"object"==typeof e&&null!==e&&"body"in e;function ma(e){if(!function(e){return"checkoutcomkey"in e}(e))throw new ni(ei.MissingPaymentMethod)}var ya=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ga extends ea{constructor(e,t){super("checkoutltd",e),this._requestSender=t}processAdditionalAction(e){return new Promise((t,n)=>{if(pa(e)&&function(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;return"string"==typeof(null===(t=n.three_ds_result)||void 0===t?void 0:t.acs_url)&&"string"==typeof n.three_ds_result.code}(e.body)&&"three_d_secure_required"===e.body.three_ds_result.code)return window.location.assign(e.body.three_ds_result.acs_url);n(e)})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ya(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new vi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"protocolVersion"in e&&"signature"in e&&"signedMessage"in e}(e))throw new ni(ei.MissingPaymentToken)}(i),n.nonce=yield this._tokenize(i),n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return ma(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.checkoutcomkey}}_tokenize(e){return ya(this,void 0,void 0,function*(){const t=this.getPaymentMethod().config.testMode?"https://api.sandbox.checkout.com/tokens":"https://api.checkout.com/tokens",n=this.getGooglePayInitializationData();ma(n);const{body:i}=yield this._requestSender.post(t,{credentials:!1,body:{type:"googlepay",token_data:e},headers:{Authorization:n.checkoutcomkey,"Content-Type":mr.Json,"X-XSRF-TOKEN":null}});return i.token})}}const fa=fi(e=>{const t=n();return new ra(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]);class va extends ea{constructor(e){super("cybersource",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const _a=fi(e=>new ra(e,new aa(da(),new va(e),n(),Ee())),[{id:"googlepaycybersourcev2"}]),Sa=fi(e=>new ra(e,new aa(da(),new va(e),n(),Ee())),[{id:"googlepaybnz"}]);class Ia extends ea{constructor(e){super("chase",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const wa=fi(e=>new ra(e,new aa(da(),new Ia(e),n(),Ee())),[{id:"googlepayorbital"}]);var Ca,ba,Pa,Oa,Ea,Aa,Ta,ka,Da,Ma,za,xa;!function(e){e.SHIPPING="shipping",e.BILLING="billing"}(Ca||(Ca={})),function(e){e.SPLIT="split",e.FULL="full",e.ORGANIZATION="organization"}(ba||(ba={})),function(e){e.Open="open",e.Expired="expired",e.Complete="complete"}(Pa||(Pa={})),function(e){e.Paid="paid",e.UnPaid="unpaid",e.NoPaymentRequired="no_payment_required"}(Oa||(Oa={})),function(e){e.SUCCESS="success",e.ERROR="error"}(Ea||(Ea={})),function(e){e.CreditCard="card",e.ACH="us_bank_account",e.Link="link",e.EPS="eps",e.GRABPAY="grabpay",e.BANCONTACT="bancontact",e.IDEAL="ideal",e.ALIPAY="alipay",e.KLARNA="klarna",e.OCS="optimized_checkout",e.CHECKOUT_SESSION="checkout_session"}(Aa||(Aa={})),function(e){e.NEVER="never",e.AUTO="auto",e.ALWAYS="always",e.PAYMENT="payment",e.IF_REQUIRED="if_required"}(Ta||(Ta={})),function(e){e.V3="v3",e.ACACIA="acacia",e.BASIL="basil",e.CLOVER="clover"}(ka||(ka={})),function(e){e.PAYMENT="payment",e.AUTHENTICATION="linkAuthentication",e.SHIPPING="address",e.EXPRESS_CHECKOUT="expressCheckout"}(Da||(Da={})),function(e){e.REQUIRES_PAYMENT_METHOD="requires_payment_method",e.REQUIRES_CONFIRMATION="requires_confirmation",e.REQUIRES_ACTION="requires_action",e.PROCESSING="processing",e.SUCCEEDED="succeeded",e.CANCELED="canceled"}(Ma||(Ma={})),function(e){e.CLICK="click",e.CHANGE="change",e.READY="ready",e.SHIPPING_ADDRESS_CHANGE="shippingaddresschange",e.SHIPPING_RATE_CHANGE="shippingratechange",e.CONFIRM="confirm",e.CANCEL="cancel",e.LOADER_START="loaderstart"}(za||(za={})),function(e){e.ON_SESSION="on_session",e.OFF_SESSION="off_session"}(xa||(xa={}));var Na=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ra{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}getStripeClient(e,t,n,i,r){return Na(this,void 0,void 0,function*(){if(this.stripeWindow.bcStripeClient)return this.stripeWindow.bcStripeClient;const o=yield this.load(n),{stripePublishableKey:a,stripeConnectedAccount:s}=e,d=o(a,Object.assign(Object.assign(Object.assign(Object.assign({},s?{stripeAccount:s}:{}),t?{locale:t}:{}),i?{betas:i}:{}),r?{apiVersion:r}:{}));return Object.assign(this.stripeWindow,{bcStripeClient:d}),d})}getElements(e,t){return Na(this,void 0,void 0,function*(){let n=this.stripeWindow.bcStripeElements;return n?yield this.updateStripeElements(t):(n=e.elements(t),Object.assign(this.stripeWindow,{bcStripeElements:n})),n})}updateStripeElements(e){return Na(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeElements;t&&(t.update(e),yield t.fetchUpdates())})}getStripeCheckout(e,t){return Na(this,void 0,void 0,function*(){let n=yield this.getStoredStripeCheckout(t);return n||(n=yield e.initCheckout(t),Object.assign(this.stripeWindow,{bcStripeCheckout:n})),n})}load(e){return Na(this,void 0,void 0,function*(){if(!this.stripeWindow.Stripe&&(yield this.scriptLoader.loadScript(this.getScriptUrl(e)),!this.stripeWindow.Stripe))throw new mi;return this.stripeWindow.Stripe})}getScriptUrl(e){return e&&e!==ka.V3?`https://js.stripe.com/${e}/stripe.js`:"https://js.stripe.com/v3/"}getStoredStripeCheckout(e){return Na(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeCheckout;if(t)try{const{actions:n,error:i}=yield t.loadActions();if(i||!n)return void this.logErrorToConsole(i);const r=yield n.getSession(),o=e.clientSecret.split("_secret_")[0];if(r.id===o)return t}catch(e){return void this.logErrorToConsole(e)}})}logErrorToConsole(e){e?console.error(e):console.error("No stripe checkout actions available on loadActions().")}}const Fa=["payment_element_beta_2","alipay_pm_beta_1","link_default_integration_beta_1","shipping_address_element_beta_1","address_element_beta_1"],La="2020-03-02;alipay_beta=v1;link_beta=v1";function ja(e){if(!function(e){return"stripeConnectedAccount"in e&&"stripePublishableKey"in e&&"stripeVersion"in e}(e))throw new ni(ei.MissingPaymentMethod)}var Ba=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ua extends ea{constructor(e,t){super("stripe",e),this.paymentIntegrationService=e,this.scriptLoader=t}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return Ba(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new vi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"id"in e}(e))throw new ni(ei.MissingPaymentToken)}(i),n.nonce=i.id,n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();ja(e);const{stripeVersion:t,stripePublishableKey:n,stripeConnectedAccount:i}=e;return{gateway:this.getGatewayIdentifier(),"stripe:version":t,"stripe:publishableKey":`${n}/${i}`}}processAdditionalAction(e,t){var n;return Ba(this,void 0,void 0,function*(){if(!t)throw new co(["payment"]);if(!pa(e)||("object"!=typeof(i=e.body)||null===i||!("three_ds_result"in i)||!("errors"in i)))throw e;var i;if(fe(e.body.errors,{code:"three_d_secure_required"})){const i=this.getGooglePayInitializationData();ja(i),this.stripeUPEClient=yield this.loadStripeJs(i,t);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this.stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this.stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if(null==o?void 0:o.error){if(this._throwDisplayableStripeError(o.error),this._isCancellationError(o.error))throw new Wi;throw new Qr}if(!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;return this.paymentIntegrationService.submitPayment({methodId:t,paymentData:{nonce:(null===(n=null==o?void 0:o.paymentIntent)||void 0===n?void 0:n.id)||r}})}throw e})}loadStripeJs(e,t){return Ba(this,void 0,void 0,function*(){if(this.stripeUPEClient)return this.stripeUPEClient;const n=this.paymentIntegrationService.getState().getCartLocale();return"googlepaystripeocs"===t&&e.useNewStripeJsVersion?this.scriptLoader.getStripeClient(e,n,ka.CLOVER):this.scriptLoader.getStripeClient(e,n,ka.V3,Fa,La)})}_isCancellationError(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))}_throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}}const qa=fi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeocs"}]),Va=fi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripeupe"}]);class Ga extends ea{constructor(e){super("worldpay",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Ha=fi(e=>new ra(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]);var Wa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $a extends ea{constructor(e,t){super("braintree",e),this._braintreeSdk=t,this._methodId=Qo.BRAINTREE,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Wa(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);let r=i.getPaymentMethod.call(this);if(r.clientToken||(r=(yield this._service.loadPaymentMethod(this._methodId)).getPaymentMethodOrThrow(this._methodId)),!r.clientToken||!r.initializationData)throw new ni(ei.MissingPaymentMethod);return this._braintreeSdk.initialize(r.clientToken),this._braintreeGooglePayment=yield this._braintreeSdk.getBraintreeGooglePayment(),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});var n;return Wa(this,void 0,void 0,function*(){const i=yield t.getNonce.call(this,e),{clientToken:r,initializationData:o}=t.getPaymentMethod.call(this);if(!r||!o||!(null===(n=o.card_information)||void 0===n?void 0:n.bin))throw new ni(ei.MissingPaymentMethod);const{isThreeDSecureEnabled:a,card_information:{bin:s,isNetworkTokenized:d}}=o;if(a&&!d){const e=yield this._braintreeSdk.getBraintreeThreeDS(),{orderAmount:t}=this._service.getState().getOrderOrThrow();return(yield this._braintreePresent3DSChallenge(e,t,i,s)).nonce}return i})}extraPaymentData(){return Wa(this,void 0,void 0,function*(){return{deviceSessionId:yield this._getBraintreeDeviceData()}})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return Wa(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new vi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"androidPayCards"in e}(e))throw new ni(ei.MissingPaymentToken)}(i),n.nonce=i.androidPayCards[0].nonce,n.card_information.bin=i.androidPayCards[0].details.bin,n.card_information.isNetworkTokenized=i.androidPayCards[0].details.isNetworkTokenized,n})}getCardParameters(){return super.getCardParameters()}getPaymentGatewayParameters(){const e=Object.create(null,{getMerchantInfo:{get:()=>super.getMerchantInfo},getTransactionInfo:{get:()=>super.getTransactionInfo},getRequiredData:{get:()=>super.getRequiredData}});return Wa(this,void 0,void 0,function*(){return this.getBraintreeGooglePayment().createPaymentDataRequest(Object.assign({merchantInfo:e.getMerchantInfo.call(this),transactionInfo:e.getTransactionInfo.call(this),cardRequirements:{billingAddressRequired:!0,billingAddressFormat:"FULL"}},yield e.getRequiredData.call(this))).paymentMethodTokenizationParameters.parameters})}getBraintreeGooglePayment(){if(!this._braintreeGooglePayment)throw new ni(ei.MissingPaymentMethod);return this._braintreeGooglePayment}_getBraintreeDeviceData(){return Wa(this,void 0,void 0,function*(){const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e})}_braintreePresent3DSChallenge(e,t,n,i){return new An(e.verifyCard({amount:t,bin:i,nonce:n,onLookupComplete:(e,t)=>{t()}})).promise}}const Ya=fi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new ra(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),Ka={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},Ja=["ar_BH","ar_DZ","ar_EG","ar_JO","ar_KW","ar_MA","ar_OM","ar_QA","ar_SA","ar_TN","ar_YE","ar_AE","bg_BG","cs_CZ","da_DK","da_FO","da_GL","de_AT","de_CH","de_DE","de_LU","el_GR","en_AD","en_AE","en_AG","en_AI","en_AL","en_AM","en_AN","en_AO","en_AT","en_AU","en_AW","en_AZ","en_BB","en_BE","en_BH","en_BJ","en_BM","en_BN","en_BS","en_BT","en_BW","en_BY","en_BZ","en_C2","en_CA","en_CD","en_CG","en_CH","en_CI","en_CK","en_CL","en_CM","en_CN","en_CO","en_CR","en_CV","en_CY","en_CZ","en_DE","en_DJ","en_DK","en_DM","en_DO","en_DZ","en_EC","en_EE","en_EG","en_ER","en_ES","en_ET","en_FI","en_FJ","en_FK","en_FM","en_FO","en_FR","en_GA","en_GB","en_GD","en_GE","en_GF","en_GI","en_GL","en_GM","en_GN","en_GP","en_GR","en_GT","en_GW","en_GY","en_HK","en_HN","en_HR","en_HU","en_ID","en_IE","en_IL","en_IN","en_IS","en_IT","en_JM","en_JO","en_JP","en_KE","en_KG","en_KH","en_KI","en_KM","en_KN","en_KR","en_KW","en_KY","en_KZ","en_LA","en_LC","en_LI","en_LK","en_LS","en_LT","en_LU","en_LV","en_MA","en_MC","en_MD","en_ME","en_MG","en_MH","en_MK","en_ML","en_MN","en_MQ","en_MR","en_MS","en_MT","en_MU","en_MV","en_MW","en_MY","en_MZ","en_NA","en_NC","en_NE","en_NF","en_NG","en_NI","en_NL","en_NO","en_NP","en_NR","en_NU","en_NZ","en_OM","en_PA","en_PE","en_PF","en_PG","en_PH","en_PL","en_PM","en_PN","en_PT","en_PW","en_PY","en_QA","en_RE","en_RO","en_RS","en_RU","en_RW","en_SA","en_SB","en_SC","en_SE","en_SG","en_SH","en_SI","en_SJ","en_SK","en_SL","en_SM","en_SN","en_SO","en_SR","en_ST","en_SV","en_SZ","en_TC","en_TD","en_TG","en_TH","en_TJ","en_TM","en_TN","en_TO","en_TR","en_TT","en_TV","en_TW","en_TZ","en_UA","en_UG","en_US","en_UY","en_VA","en_VC","en_VE","en_VG","en_VN","en_VU","en_WF","en_WS","en_YE","en_YT","en_ZA","en_ZM","en_ZW","es_AD","es_AI","es_AO","es_AR","es_AW","es_BB","es_BJ","es_BM","es_BO","es_BS","es_BZ","es_CD","es_CG","es_CK","es_CL","es_CO","es_CR","es_CV","es_DJ","es_DM","es_DO","es_DZ","es_EC","es_EG","es_ER","es_ES","es_ET","es_FJ","es_FK","es_FO","es_GA","es_GD","es_GE","es_GI","es_GL","es_GM","es_GN","es_GT","es_GW","es_GY","es_HN","es_IE","es_JM","es_JO","es_KE","es_KG","es_KI","es_KM","es_KN","es_KW","es_KY","es_KZ","es_LC","es_LI","es_LS","es_LU","es_MA","es_MG","es_MH","es_ML","es_MR","es_MS","es_MU","es_MW","es_MX","es_MZ","es_NA","es_NC","es_NE","es_NF","es_NI","es_NR","es_NU","es_NZ","es_OM","es_PA","es_PE","es_PF","es_PG","es_PM","es_PN","es_PW","es_PY","es_QA","es_RS","es_RW","es_SA","es_SB","es_SC","es_SH","es_SJ","es_SL","es_SM","es_SN","es_SO","es_SR","es_ST","es_SV","es_SZ","es_TC","es_TD","es_TG","es_TJ","es_TM","es_TN","es_TT","es_TV","es_UA","es_UG","es_US","es_UY","es_VA","es_VC","es_VE","es_VG","es_VU","es_WF","es_YE","es_ZM","et_EE","fi_FI","fr_AD","fr_AE","fr_AI","fr_AM","fr_AO","fr_AW","fr_AZ","fr_BB","fr_BE","fr_BF","fr_BI","fr_BJ","fr_BM","fr_BS","fr_BZ","fr_CA","fr_CD","fr_CG","fr_CH","fr_CI","fr_CK","fr_CM","fr_CV","fr_DJ","fr_DM","fr_DO","fr_DZ","fr_EC","fr_ER","fr_ET","fr_FJ","fr_FK","fr_FO","fr_FR","fr_GA","fr_GD","fr_GE","fr_GF","fr_GI","fr_GL","fr_GM","fr_GN","fr_GP","fr_GT","fr_GW","fr_GY","fr_HN","fr_IE","fr_JM","fr_JO","fr_KE","fr_KG","fr_KI","fr_KM","fr_KN","fr_KW","fr_KY","fr_KZ","fr_LC","fr_LI","fr_LS","fr_LU","fr_MA","fr_MC","fr_MG","fr_MH","fr_ML","fr_MQ","fr_MR","fr_MS","fr_MU","fr_MW","fr_MZ","fr_NA","fr_NC","fr_NE","fr_NF","fr_NI","fr_NR","fr_NU","fr_NZ","fr_OM","fr_PA","fr_PE","fr_PF","fr_PG","fr_PM","fr_PN","fr_PW","fr_QA","fr_RE","fr_RS","fr_RW","fr_SA","fr_SB","fr_SC","fr_SH","fr_SJ","fr_SL","fr_SM","fr_SN","fr_SO","fr_SR","fr_ST","fr_SV","fr_SZ","fr_TC","fr_TD","fr_TG","fr_TJ","fr_TM","fr_TN","fr_TT","fr_TV","fr_UA","fr_UG","fr_US","fr_UY","fr_VA","fr_VC","fr_VE","fr_VG","fr_VU","fr_WF","fr_YE","fr_YT","fr_ZA","fr_ZM","he_IL","hu_HU","id_ID","it_IT","ja_JP","ko_KR","lv_LV","lt_LT","ms_BN","ms_MY","nl_BE","nl_NL","pl_PL","pt_BR","pt_PT","ro_RO","ru_EE","ru_LT","ru_LV","ru_RU","ru_UA","si_LK","sk_SK","sl_SI","sq_AL","sv_SE","tl_PH","th_TH","tr_TR","vi_VN","zh_C2","zh_CN","zh_HK","zh_TW","zh_AD","zh_AE","zh_AI","zh_AO","zh_AW","zh_BB","zh_BH","zh_BJ","zh_BM","zh_BS","zh_BZ","zh_CD","zh_CG","zh_CK","zh_CL","zh_CO","zh_CV","zh_DJ","zh_DM","zh_DO","zh_DZ","zh_EC","zh_EG","zh_ER","zh_ET","zh_FJ","zh_FK","zh_FO","zh_GA","zh_GD","zh_GE","zh_GI","zh_GL","zh_GM","zh_GN","zh_GT","zh_GW","zh_GY","zh_HN","zh_IE","zh_JM","zh_JO","zh_KE","zh_KG","zh_KI","zh_KM","zh_KN","zh_KW","zh_KY","zh_KZ","zh_LC","zh_LI","zh_LS","zh_LT","zh_LU","zh_MA","zh_MG","zh_MH","zh_ML","zh_MR","zh_MS","zh_MU","zh_MW","zh_MZ","zh_NA","zh_NC","zh_NE","zh_NF","zh_NI","zh_NR","zh_NU","zh_NZ","zh_OM","zh_PA","zh_PE","zh_PF","zh_PG","zh_PM","zh_PN","zh_PW","zh_QA","zh_RS","zh_RW","zh_SA","zh_SB","zh_SC","zh_SH","zh_SJ","zh_SL","zh_SM","zh_SN","zh_SO","zh_SR","zh_ST","zh_SV","zh_SZ","zh_TC","zh_TD","zh_TG","zh_TJ","zh_TM","zh_TN","zh_TT","zh_TV","zh_UA","zh_UG","zh_US","zh_UY","zh_VA","zh_VC","zh_VE","zh_VG","zh_VU","zh_WF","zh_YE","zh_ZA","zh_ZM"];function Za(e){if(!e)return;let t;if(e.includes("-")){const[n,i]=e.split("-");t=`${n}_${i.toUpperCase()}`}else t=`${e}_${e.toUpperCase()}`;return Ja.includes(t)?t:void 0}var Qa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xa{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n,i){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Qa(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t,intent:a},l&&{locale:l}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ni(ei.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function es(e){if(!function(e){return!!e.initializationData&&"attributionId"in e.initializationData&&"isVenmoEnabled"in e.initializationData&&"isGooglePayEnabled"in e.initializationData&&"isPayPalCreditAvailable"in e.initializationData}(e))throw new ni(ei.MissingPaymentMethod)}var ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ns extends ea{constructor(e,t){super("paypalsb",e),this.payPalCommerceSdk=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return ts(this,void 0,void 0,function*(){const c=this.service.getState(),l=null!==(o=null===(r=c.getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!l)throw new ni(ei.MissingPaymentMethod);yield i.initialize.call(this,e,t,l);const u=i.getPaymentMethod.call(this);if(!u.initializationData)throw new ni(ei.MissingPaymentMethod);es(u);const h=yield this.payPalCommerceSdk.getPayPalGooglePaySdk(u,l,c.getLocale());this.googlepayConfig=yield h.Googlepay().config();const{allowedPaymentMethods:p}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=p[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ts(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const is=fi(e=>new ra(e,new aa(da(),new ns(e,new Xa(a())),n(),Ee())),[{id:"googlepaypaypalcommerce"}]);var rs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class os extends ea{constructor(e,t){super("googlepay_bigcommerce_payments",e),this.payPalSdkHelper=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return rs(this,void 0,void 0,function*(){const c=null!==(o=null===(r=this.service.getState().getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!c)throw new ni(ei.MissingPaymentMethod);yield i.initialize.call(this,e,t,c);const l=i.getPaymentMethod.call(this);if(!l.initializationData)throw new ni(ei.MissingPaymentMethod);es(l);const u=yield this.payPalSdkHelper.getPayPalGooglePaySdk(l,c);this.googlepayConfig=yield u.Googlepay().config();const{allowedPaymentMethods:h}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=h[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return rs(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const as=fi(e=>new ra(e,new aa(da(),new os(e,new Nr(a())),n(),Ee())),[{id:"googlepay_bigcommerce_payments"}]);function ss(){const{navigator:e}=window;let t;return t=e.language?e.language:e.userLanguage,{color_depth:window.screen.colorDepth||24,java_enabled:"function"==typeof e.javaEnabled&&e.javaEnabled(),language:t,screen_height:window.screen.height,screen_width:window.screen.width,time_zone_offset:(new Date).getTimezoneOffset().toString()}}var ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cs extends ea{constructor(e,t){super("worldlinena",e),this.formPoster=t}extraPaymentData(){return ds(this,void 0,void 0,function*(){return Promise.resolve({browser_info:ss()})})}processAdditionalAction(e){return ds(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&fe(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}}const ls=fi(e=>new ra(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);var us,hs,ps,ms,ys,gs,fs,vs,_s,Ss,Is=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ws{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return Is(this,void 0,void 0,function*(){if(!this.window.paypal||r){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypal)throw new mi}return this.window.paypal})}getPayPalFastlaneSdk(e,t,n,i){return Is(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return Is(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return Is(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return Is(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Is(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!a||!a.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:f=[],isGooglePayEnabled:v}=a,_=p||i,S="paypalcommercecreditcards"===r||"bigcommerce_payments_creditcards"===r,I=S?["card"]:[],w=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=v?["googlepay"]:[],P=i?["card-fields"]:[],O=[...S?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!f.includes(e))],E=[...I,...w,...C,...f],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:_,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t},l&&{locale:l}),{intent:a}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ni(ei.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Cs(){return new ws(o())}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(us||(us={})),(hs||(hs={})).Always="SCA_ALWAYS",function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(ps||(ps={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ms||(ms={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(ys||(ys={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(gs||(gs={})),function(e){e.pill="pill",e.rect="rect"}(fs||(fs={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(vs||(vs={})),(_s||(_s={})).OXXO="oxxo",function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(Ss||(Ss={}));var bs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ps{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalRequestSender=n,this.paypalSdkLoader=i}loadPayPalSdk(e,t,n,i){return bs(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e),s=r.getLocale();return this.paypalSdk=yield this.paypalSdkLoader.getPayPalSDK(a,o,s,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return bs(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ni(ei.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(e,t,n){return bs(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getConsignmentsOrThrow()[0];try{yield this.paypalRequestSender.updateOrder(e,Object.assign(Object.assign({availableShippingOptions:o.availableShippingOptions,cartId:r.id,selectedShippingOption:o.selectedShippingOption},t?{methodId:t}:{}),n?{orderId:n}:{}))}catch(e){throw new nr}})}getOrderStatus(e,t){return bs(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ni(ei.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===Rt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return bs(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{if(t.selectedShippingOption){const n=t.selectedShippingOption.id;return e.id===n}return!1}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e={}){const{color:t,height:n,label:i,shape:r}=e,o={color:t&&gs[t]?t:void 0,height:this.getValidHeight(n),label:i&&ys[i]?i:void 0,shape:r&&fs[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Os=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Es{constructor(e){this.requestSender=e}createOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put(n,{headers:r,body:i})).body})}getOrderStatus(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}const As=e=>{const{getHost:t}=e.getState();return new Ps(Ee(),e,new Es(n({host:t()})),Cs())};var Ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const ks=class{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}createPayPalButton(e,t,n,i){const{style:r,fundingSource:o,isAppSwitchEnabled:a,isHostedCheckoutEnabled:s,onClick:d,onCancel:c,onPaymentComplete:l,onError:u}=n;this.onError=u;const h=this.paypalIntegrationService.getPayPalSdkOrThrow();if(!Object.values(h.FUNDING).includes(o))throw new vi('Unable to initialize PayPal button because "fundingSource" argument is not valid funding source.');const p=Object.assign(Object.assign({},!a&&{onShippingAddressChange:t=>this.onShippingAddressChange(t,e),onShippingOptionsChange:t=>this.onShippingOptionsChange(t,e)}),{onApprove:(n,i)=>this.onHostedCheckoutApprove(n,i,t,e,l)});return h.Buttons(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({fundingSource:o,style:this.paypalIntegrationService.getValidButtonStyle(r)},a&&{appSwitchWhenAvailable:!0}),{createOrder:()=>Ts(this,void 0,void 0,function*(){if(i){const e=yield this.paypalIntegrationService.createBuyNowCartOrThrow(i);yield this.paymentIntegrationService.loadCheckout(e.id)}return this.paypalIntegrationService.createOrder(e)}),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)}),d?{onClick:d}:{}),c?{onCancel:c}:{}),s&&p))}onHostedCheckoutApprove(e,t,n,i,r){return Ts(this,void 0,void 0,function*(){if(!e.orderID)throw new ni(ei.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),a=yield t.order.get();try{const t=this.paypalIntegrationService.getBillingAddressFromOrderDetails(a);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.paypalIntegrationService.getShippingAddressFromOrderDetails(a);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalIntegrationService.updateOrder(i)}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalIntegrationService.submitPayment(n,e.orderID),r&&"function"==typeof r&&r()}catch(e){this.handleError(e)}})}onShippingAddressChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(n),yield this.paymentIntegrationService.updateShippingAddress(n);const e=this.paypalIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}onShippingOptionsChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(n.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}};var Ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ms{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalButtonCreationService=n}initialize(e){return Ds(this,void 0,void 0,function*(){const{paypalcommerce:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.paypalcommerce.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.paypalcommerce.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ds(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Ds(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()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a,onError:s}=t,d=this.paypalIntegrationService.getPayPalSdkOrThrow(),c=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:l,paymentButtonStyles:u,isAppSwitchEnabled:h}=c.initializationData||{},{checkoutTopButtonStyles:p}=u||{},m=Object.assign(Object.assign(Object.assign({fundingSource:d.FUNDING.PAYPAL,isAppSwitchEnabled:h,isHostedCheckoutEnabled:l,style:Object.assign(Object.assign({},p),{height:Ir})},o&&{onClick:()=>o()}),l&&a&&{onPaymentComplete:()=>a()}),{onError:s}),y=this.paypalButtonCreationService.createPayPalButton("paypalcommerce",e,m);y.isEligible()?(null===(n=y.hasReturned)||void 0===n?void 0:n.call(y))&&h?null===(i=y.resume)||void 0===i||i.call(y):y.render(`#${r}`):this.paypalIntegrationService.removeElement(r)}}const zs=fi(e=>{const t=As(e),n=new ks(e,t);return new Ms(e,t,n)},[{id:"paypalcommerce"}]);var xs,Ns,Rs,Fs,Ls,js,Bs;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(xs||(xs={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Ns||(Ns={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Rs||(Rs={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Fs||(Fs={})),function(e){e.pill="pill",e.rect="rect"}(Ls||(Ls={})),function(e){e.OXXO="oxxo",e.IDEAL="ideal"}(js||(js={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(Bs||(Bs={}));var Us=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qs{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=i}loadPayPalSdk(e,t,n,i){return Us(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.paypalCommerceScriptLoader.getPayPalSDK(a,o,r.getLocale(),n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return Us(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ni(ei.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return Us(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return Us(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalCommerceRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ni(ei.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===Rt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return Us(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&Fs[t]?t:void 0,height:this.getValidHeight(n),label:i&&Rs[i]?i:void 0,shape:r&&Ls[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Vs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gs{constructor(e){this.requestSender=e}createOrder(e,t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return Vs(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:t})).body})}getOrderStatus(e="paypalcommerce",t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var Hs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ws{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return Hs(this,void 0,void 0,function*(){const o=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);return this.loadPayPalSDK(o,r)})}loadPayPalSDK(e,t=!1){return Hs(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.paypal)throw new mi;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!(null==a?void 0:a.clientId))throw new ni(ei.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:f=[],isGooglePayEnabled:v}=a,_=p||i,S="paypalcommercecreditcards"===r,I=S?["card"]:[],w=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=v?["googlepay"]:[],P=i?["card-fields"]:[],O=[...S?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!f.includes(e))],E=[...I,...w,...C,...f],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:_,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const $s=e=>{const{getHost:t}=e.getState();return new qs(Ee(),e,new Gs(n({host:t()})),new Ws(a()))};var Ys=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ks{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=ce}initialize(e){return Ys(this,void 0,void 0,function*(){const{paypalcommercecredit:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.paypalcommercecredit.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.paypalcommercecredit.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ys(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Ys(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()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d,isAppSwitchEnabled:c}=a.initializationData||{},{checkoutTopButtonStyles:l}=d||{},u=Object.assign({createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),h=Object.assign(Object.assign({},!c&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)}),p=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let m=!1;p.forEach(e=>{if(!m){const t=Object.assign(Object.assign({fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},l),{height:Ir}))},u),s&&h),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),m=!0)}}),m||this.paypalCommerceIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Ys(this,void 0,void 0,function*(){if(!e.orderID)throw new ni(ei.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalCommerceIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalCommerceIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Js=fi(e=>new Ks(e,$s(e)),[{id:"paypalcommercecredit"}]);var Zs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Qs{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return Zs(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.paypalcommercevenmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.paypalcommercevenmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Zs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Zs(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()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:Ir})),createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.paypalCommerceIntegrationService.removeElement(n)}}const Xs=fi(e=>new Qs(e,$s(e)),[{id:"paypalcommercevenmo"}]);var ed=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class td{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return ed(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.paypalFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.paypalFastlane=yield e.Fastlane({styles:n||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new mi;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return ed(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return ed(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||vs.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function nd(){return new td}function id(e){return"string"!=typeof e}function rd(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,id),o=ue(e.input,id),a=ue(e.toggle,id),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,id),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,id),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,f,v,_,S,I,w,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.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===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.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===(p=null==t?void 0:t.input)||void 0===p?void 0:p.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===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(f=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===f?void 0:f.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(_=null===(v=null==t?void 0:t.text)||void 0===v?void 0:v.body)||void 0===_?void 0:_.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(S=null==t?void 0:t.text)||void 0===S?void 0:S.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var od=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ad{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalSdkScriptLoader=t,this.paypalFastlaneUtils=n}initialize(e){var t;return od(this,void 0,void 0,function*(){const{methodId:n,paypalcommercefastlane:i}=e;if(!n)throw new vi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(o,r.currency.code,r.id,e.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return od(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.paypalFastlaneUtils.removeStorageSessionId()})}signOut(e){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return od(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new vi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new vi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return od(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.paypalFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===vs.CANCELED;yield this.updateCustomerDataState(e,s),d?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return od(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.paypalFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return rd(r?i:{},null==t?void 0:t.styles)}}const sd=fi(e=>new ad(e,Cs(),nd()),[{id:"paypalcommerceacceleratedcheckout"},{id:"paypalcommercecreditcards"}]);function dd(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&void 0!==e.initializationData&&null!==e.initializationData&&"object"==typeof e.initializationData&&"stripePublishableKey"in e.initializationData&&"stripeConnectedAccount"in e.initializationData&&"shopperLanguage"in e.initializationData&&void 0!==e.initializationData.stripePublishableKey&&void 0!==e.initializationData.stripeConnectedAccount&&void 0!==e.initializationData.shopperLanguage}function cd(e){return"stripeLinkAuthenticationState"in e}class ld{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){var t,n,i,r,o;return n=this,i=void 0,o=function*(){let n;if(!e.stripeupe)throw new vi('Unable to proceed because "options" argument is not provided.');const{container:i,gatewayId:r,methodId:o,onEmailChange:a,getStyles:s,isLoading:d}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new vi(`Unable to proceed because "${e}" argument is not provided.`)}),yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:o}});const c=this.paymentIntegrationService.getState(),l=c.getPaymentMethodOrThrow(o,r),{clientToken:u}=l;if(!dd(l)||!u)throw new ni(ei.MissingPaymentToken);const{email:h}=c.getCustomerOrThrow(),p=c.getPaymentProviderCustomerOrThrow(),m=(cd(p)?p:{}).stripeLinkAuthenticationState;if(!h){let e;const r="function"==typeof s&&s();e=r?{variables:{colorPrimary:r.fieldInnerShadow,colorBackground:r.fieldBackground,colorText:r.labelText,colorDanger:r.fieldErrorText,colorTextSecondary:r.labelText,colorTextPlaceholder:r.fieldPlaceholderText},rules:{".Input":{borderColor:r.fieldBorder,color:r.fieldText,boxShadow:r.fieldInnerShadow}}}:{},n=yield this.scriptLoader.getStripeClient(l.initializationData,c.getCartLocale(),ka.V3,Fa,La),this._stripeElements=yield this.scriptLoader.getElements(n,{clientSecret:u,appearance:e});const{getBillingAddress:o,getConsignments:h}=this.paymentIntegrationService.getState(),p=h(),y=null===(t=null==p?void 0:p[0])||void 0===t?void 0:t.id,{email:g}=o()||{},f=g?{defaultValues:{mode:Ca.SHIPPING,email:g}}:{},v=this._stripeElements.getElement(Da.AUTHENTICATION)||this._stripeElements.create(Da.AUTHENTICATION,f);v.on(za.CHANGE,e=>{if(!("authenticated"in e))throw new ni(ei.MissingCustomer);this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:e.authenticated}),e.complete?a(e.authenticated,e.value.email):a(!1,""),d&&d(!1),void 0===m&&e.authenticated&&y&&this.paymentIntegrationService.deleteConsignment(y)}),v.mount(`#${i}`)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Da.AUTHENTICATION))||void 0===t||t.unmount(),Promise.resolve()}signIn(e,t){return this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()}signOut(e){return 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()}}const ud=fi(e=>new ld(e,new Ra(a())),[{id:"stripeupe"}]);var hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pd{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.isMounted=!1}deinitialize(){var e;null===(e=this.checkoutEventsUnsubscribe)||void 0===e||e.call(this),this.isMounted=!1}initCheckoutEventsSubscription(e,t,n,i){this.checkoutEventsUnsubscribe=this.paymentIntegrationService.subscribe(()=>hd(this,void 0,void 0,function*(){var r;const o=null==i?void 0:i.getElement(Da.PAYMENT);if(o){try{yield this.updateStripePaymentIntent(e,t)}catch(e){return this.isMounted&&(o.unmount(),this.isMounted=!1),void(e instanceof Error&&(null===(r=n.onError)||void 0===r||r.call(n,e)))}this.isMounted||(yield null==i?void 0:i.fetchUpdates(),this.mountElement(o,n.containerId))}}),e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.outstandingBalance},e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.coupons})}mountElement(e,t){document.getElementById(t)&&(e.mount(`#${t}`),this.isMounted=!0)}mapAppearanceVariables(e){return{colorPrimary:e.fieldInnerShadow,colorBackground:e.fieldBackground,colorText:e.labelText,colorDanger:e.fieldErrorText,colorTextSecondary:e.labelText,colorTextPlaceholder:e.fieldPlaceholderText,colorIcon:e.fieldPlaceholderText}}mapInputAppearanceRules(e){return{borderColor:e.fieldBorder,color:e.fieldText,boxShadow:e.fieldInnerShadow}}throwStripeError(e){if("object"==typeof(t=e)&&null!==t&&"type"in t&&(this.throwDisplayableStripeError(e),this.isCancellationError(e)))throw new Wi;var t;throw new Qr}throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}isCancellationError(e){var t;const n=null===(t=null==e?void 0:e.payment_intent.last_payment_error)||void 0===t?void 0:t.message;return!!n&&-1!==n.indexOf("canceled")}throwPaymentConfirmationProceedMessage(){throw new Qr("We've received your order and are processing your payment. Once the payment is verified, your order will be completed. We will send you an email when it's completed. Please note, this process may take a few minutes depending on the processing times of your chosen method.")}isPaymentCompleted(e,t){return hd(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(e),{features:r}=n.getStoreConfigOrThrow().checkoutSettings;if(!i.clientToken||!t||!r["PI-626.Block_unnecessary_payment_confirmation_for_StripeUPE"])return!1;const{paymentIntent:o}=yield t.retrievePaymentIntent(i.clientToken);return(null==o?void 0:o.status)===Ma.SUCCEEDED})}mapStripePaymentData(e,t,n=!1){const i=this.paymentIntegrationService.getState().getBillingAddress(),{firstName:r="",lastName:o="",email:a=""}=i||{},s=this.mapStripeAddress(i);if(!e)throw new ri(ti.PaymentNotInitialized);if(!(a&&s&&s.city&&s.country&&r&&o))throw new ni(ei.MissingBillingAddress);return{elements:e,redirect:Ta.IF_REQUIRED,confirmParams:Object.assign({payment_method_data:Object.assign(Object.assign({},n?{allow_redisplay:"always"}:{}),{billing_details:{email:a,address:s,name:this.getShopperFullName(i)}})},t&&{return_url:t})}}isAdditionalActionError(e){return fe(e,{code:"additional_action_required"})}isRedirectAction(e){const{type:t,data:{redirect_url:n}}=e;return"redirect_to_url"===t&&!!n}isOnPageAdditionalAction(e){const{type:t,data:{token:n}}=e;return"additional_action_requires_payment_method"===t&&!!n}updateStripePaymentIntent(e,t){return hd(this,void 0,void 0,function*(){const n=yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}}),{clientToken:i}=n.getPaymentMethodOrThrow(t);i&&this.scriptLoader.updateStripeElements({clientSecret:i})})}getStripeJsVersion(e){return e.useNewStripeJsVersion?ka.CLOVER:ka.V3}mapStripeAddress(e){if(e){const{city:t,address1:n,address2:i,countryCode:r,postalCode:o,stateOrProvinceCode:a}=e;return Object.assign({city:t,country:r,postal_code:o,line1:n,line2:i},a?{state:a}:{})}throw new ni(ei.MissingBillingAddress)}getShopperFullName(e){const{firstName:t="",lastName:n=""}=e||{};return`${t} ${n}`.trim()}}const md={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},yd={position:"fixed","background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},gd="embedded-checkout-loading-indicator-rotation";class fd{constructor(e){this.styles=Object.assign(Object.assign({},md),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=`${gd} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(n=>{e.style.setProperty(n,t[n])})}defineAnimation(){var e;if(document.getElementById(gd))return;const t=document.createElement("style");t.id=gd,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${gd} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}class vd{constructor(e){this._decimalPlaces=e}toInteger(e){return Math.round(e*Math.pow(10,this._decimalPlaces))}}const _d=["AC","AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CV","CW","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MK","ML","MM","MN","MO","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SZ","TA","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","US","UY","UZ","VA","VC","VE","VG","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW","ZZ"];var Sd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Id{constructor(e,t,n,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n,this.loadingIndicator=i}initialize(e){return Sd(this,void 0,void 0,function*(){const{stripeocs:t}=e||{};if(!t)throw new vi('Unable to proceed because "options" argument is not provided.');const{gatewayId:n,container:i}=t;if(!i||!n)throw new ri(ti.PaymentNotInitialized);const r=this._getMethodId(n),o=yield this.paymentIntegrationService.loadPaymentMethod(n,{params:{method:r}}),a=o.getPaymentMethodOrThrow(r,n),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!dd(a))throw new ni(ei.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this._mountExpressCheckoutElement(i,this._stripeClient,d),this._initializeEvents(r)})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,n=40){return Sd(this,void 0,void 0,function*(){const i=this._shouldRequireShippingAddress(),r=Object.assign(Object.assign(Object.assign({shippingAddressRequired:i},i?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),i?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ta.AUTO,applePay:Ta.NEVER,googlePay:Ta.NEVER,amazonPay:Ta.NEVER,paypal:Ta.NEVER,klarna:Ta.NEVER},buttonHeight:n}),{cartAmount:o}=this.paymentIntegrationService.getState().getCartOrThrow(),a=Object.assign({mode:"payment",amount:this._toCents(o),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});return this._stripeElements=t.elements(a),this._linkV2Element=this._stripeElements.create(Da.EXPRESS_CHECKOUT,r),this._linkV2Element.mount(`#${e}`),this._linkV2Element})}_initializeEvents(e){this._linkV2Element&&(this._shouldRequireShippingAddress()&&(this._linkV2Element.on(za.SHIPPING_ADDRESS_CHANGE,e=>Sd(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),this._linkV2Element.on(za.SHIPPING_RATE_CHANGE,e=>Sd(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),this._linkV2Element.on(za.CONFIRM,t=>Sd(this,void 0,void 0,function*(){return this._onConfirm(t,e)})),this._linkV2Element.on(za.CANCEL,this._onCancel))}_onShippingAddressChange(e){return Sd(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,n={firstName:"",lastName:"",phone:"",company:"",address1:"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.country)||"",postalCode:(null==t?void 0:t.postal_code)||"",stateOrProvince:(null==t?void 0:t.state)||"",stateOrProvinceCode:(null==t?void 0:t.state)||"",customFields:[]};yield this.paymentIntegrationService.updateShippingAddress(n);const i=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==i?void 0:i.length)?e.resolve({shippingRates:i}):e.reject()})}_onCancel(){throw new Wi}_onShippingRateChange(e){return Sd(this,void 0,void 0,function*(){if("shippingRate"in e){const{shippingRate:t}=e;yield this._handleShippingOptionChange(null==t?void 0:t.id),yield this._updateDisplayedPrice(),e.resolve({})}})}_onConfirm(e,t){return Sd(this,void 0,void 0,function*(){if("billingDetails"in e&&"shippingAddress"in e&&this._stripeClient&&this._stripeElements){yield this._updateShippingAndBillingAddress(e),yield this.paymentIntegrationService.submitOrder();const n=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(n)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,n,i,r,o,a,s,d;return Sd(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(n=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===n?void 0:n.split(" ")[0])||(null===(r=null===(i=e.billingDetails)||void 0===i?void 0:i.name)||void 0===r?void 0:r.split(" ")[0])||"",u=(null===(a=null===(o=e.shippingAddress)||void 0===o?void 0:o.name)||void 0===a?void 0:a.split(" ")[1])||(null===(d=null===(s=e.billingDetails)||void 0===s?void 0:s.name)||void 0===d?void 0:d.split(" ")[1])||"";if(c){const t=this._mapShippingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateShippingAddress(t)}const h=this._mapBillingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateBillingAddress(h)})}_mapShippingAddress(e,t,n,i){var r,o,a,s,d,c,l;return{firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==e?void 0:e.address)||void 0===r?void 0:r.line1)||"",address2:(null===(o=null==e?void 0:e.address)||void 0===o?void 0:o.line2)||"",city:(null===(a=null==e?void 0:e.address)||void 0===a?void 0:a.city)||"",countryCode:(null===(s=null==e?void 0:e.address)||void 0===s?void 0:s.country)||"",postalCode:(null===(d=null==e?void 0:e.address)||void 0===d?void 0:d.postal_code)||"",stateOrProvince:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",stateOrProvinceCode:(null===(l=null==e?void 0:e.address)||void 0===l?void 0:l.state)||"",customFields:[]}}_mapBillingAddress(e,t,n,i){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==t?void 0:t.address)||void 0===r?void 0:r.line1)||"",address2:"",city:(null===(o=null==t?void 0:t.address)||void 0===o?void 0:o.city)||"",countryCode:(null===(a=null==t?void 0:t.address)||void 0===a?void 0:a.country)||"",postalCode:(null===(s=null==t?void 0:t.address)||void 0===s?void 0:s.postal_code)||"",stateOrProvince:(null===(d=null==t?void 0:t.address)||void 0===d?void 0:d.state)||"",stateOrProvinceCode:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",customFields:[]}}_processAdditionalAction(e,t){return Sd(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new ri(ti.PaymentNotInitialized);const{data:n}=e.body.additional_action_required,{token:i}=n,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(n,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||i);try{this._toggleLoadingIndicator(!0),yield this.paymentIntegrationService.submitPayment(o),yield this._completeCheckoutFlow()}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}finally{this._toggleLoadingIndicator(!1)}})}_confirmStripePaymentOrThrow(e,t){var n,i,r;return Sd(this,void 0,void 0,function*(){const{token:o,redirect_url:a}=e,s=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,a);let d;try{const e=(yield this.stripeIntegrationService.isPaymentCompleted(t,this._stripeClient))?yield null===(r=this._stripeClient)||void 0===r?void 0:r.retrievePaymentIntent(o||""):yield null===(n=this._stripeClient)||void 0===n?void 0:n.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ta.IF_REQUIRED,confirmParams:{return_url:null===(i=s.confirmParams)||void 0===i?void 0:i.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Qr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return Sd(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var n;const i=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:i},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:Aa.Link})}}}_shouldRequireShippingAddress(){const{getCartOrThrow:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e();return!!t.physicalItems.length}_updateDisplayedPrice(){return Sd(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){if(!this._currencyCode){const{code:e}=this.paymentIntegrationService.getState().getCartOrThrow().currency;this._currencyCode=e.toLowerCase()}return this._currencyCode}_getTotalPrice(){return Sd(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:e,getCartOrThrow:t}=this.paymentIntegrationService.getState(),{decimalPlaces:n}=t().currency,i=ge(e().outstandingBalance,n).toFixed(n);return this._toCents(+i)})}_getAvailableCountries(){var e;return Sd(this,void 0,void 0,function*(){const t=yield this.paymentIntegrationService.loadShippingCountries();return((null===(e=t.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code))||[]).filter(e=>_d.includes(e))})}_getAvailableShippingOptions(){var e,t,n;return Sd(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const r=i[0],o=(r.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),a=null===(e=r.availableShippingOptions)||void 0===e?void 0:e.find(e=>e.isRecommended),s=null===(t=r.selectedShippingOption)||void 0===t?void 0:t.id,d=null==a?void 0:a.id;return s?o.sort(e=>e.id===s?-1:0):d?(o.sort(e=>e.id===d?-1:0),yield this._handleShippingOptionChange(d)):yield this._handleShippingOptionChange(null===(n=o[0])||void 0===n?void 0:n.id),o.slice(0,9)})}_getStripeShippingOption({id:e,cost:t,description:n}){return{id:e,displayName:n,amount:this._toCents(t)}}_handleShippingOptionChange(e){return Sd(this,void 0,void 0,function*(){if(e&&"shipping_option_unselected"!==e)return this.paymentIntegrationService.selectShippingOption(e)})}_getAmountTransformer(){if(this._amountTransformer)return this._amountTransformer;const{getCart:e}=this.paymentIntegrationService.getState(),{currency:t}=e()||{};return t?new vd(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),n=this._getAmountTransformer();return n?n.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}_getMethodId(e){const{initializationData:{checkoutSessionEnabled:t}={}}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return t?Aa.CHECKOUT_SESSION:Aa.OCS}}const wd=fi(e=>{const t=new Ra(a()),n=new fd({containerStyles:yd});return new Id(e,t,new pd(e,t),n)},[{id:"stripeocs"}]);class Cd extends Xn{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}class bd{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){yield this._paymentIntegrationService.submitOrder(le(e,"payment"),t)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Pd=fi(e=>new bd(e),[{id:"nopaymentdatarequired"}]);var Od,Ed,Ad,Td,kd,Dd,Md;class zd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-8ofgICZZ/k5cC5N7xegqFZOA73H9RQ7H13439JfAZW8Gj3qjuKL2isaTD3GMIhDE",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-wG2z9zSQo61EIvyXmiFCo+zB3y0ZB4hsrXVcANmpP8HLthjoQJQPBh7tZKJSV8jA",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return new this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function xd(e){return"object"==typeof e&&"string"==typeof e.data.paymentMethod.encryptedSecurityCode||"string"==typeof e.data.paymentMethod.encryptedExpiryMonth}function Nd(e){return Boolean(e.instrumentId)}!function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2="threeDS2",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher",e.Sdk="sdk"}(Od||(Od={})),function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2Challenge="threeDS2Challenge",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher"}(Ed||(Ed={})),function(e){e.SecuredFields="securedfields"}(Ad||(Ad={})),function(e){e.ACH="ach",e.AliPay="alipay",e.Bancontact="bcmc",e.CreditCard="scheme",e.Klarna="klarna",e.KlarnaPayNow="klarna_paynow",e.KlarnaAccount="klarna_account",e.IDEAL="ideal",e.GiroPay="giropay",e.GooglePay="paywithgoogle",e.SEPA="sepadirectdebit",e.Sofort="directEbanking",e.Vipps="vipps",e.WeChatPayQR="wechatpayQR"}(Td||(Td={})),function(e){e.POST="POST"}(kd||(kd={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(Dd||(Dd={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(Md||(Md={}));var Rd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return Rd(this,void 0,void 0,function*(){const{adyenv2:t}=e;if(!t)throw new vi('Unable to initialize payment because "options.adyenv2" argument is not provided.');this._paymentInitializeOptions=t;const n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{originKey:i,clientKey:r,environment:o,paymentMethodsResponse:a}=n.initializationData||{},s={key:"",value:""};return i?(s.key="originKey",s.value=i):(s.key="clientKey",s.value=r||""),this._adyenClient=yield this._scriptLoader.load({environment:o,locale:this._paymentIntegrationService.getState().getLocale(),[s.key]:s.value,paymentMethodsResponse:a,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this._paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){return Rd(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=n&&n.paymentData,o=r&&r.shouldSaveInstrument,a=r&&r.shouldSetAsDefaultInstrument;if(!n)return Promise.reject(new co(["payment"]));this._validateCardData(),yield this._paymentIntegrationService.submitOrder(i,t);const s=this._componentState;if(!s)throw new ri(ti.PaymentNotInitialized);if(r&&Nd(r)){let e={};if(xd(s)){const{encryptedCardNumber:t,encryptedSecurityCode:n,encryptedExpiryMonth:i,encryptedExpiryYear:r}=s.data.paymentMethod;e={credit_card_number_confirmation:t,expiry_month:i,expiry_year:r,verification_value:n}}if(xd(s)||-1!==["ideal","sepadirectdebit","directEbanking","giropay"].indexOf(s.data.paymentMethod.type))try{return void(yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:{formattedPayload:{bigpay_token:Object.assign(Object.assign({},e),{token:r.instrumentId}),origin:window.location.origin,browser_info:ss(),set_as_default_stored_instrument:a||null}}})))}catch(e){return void(yield this._processAdditionalAction(e,o,a))}}try{yield this._paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify(Object.assign(Object.assign({},s.data.paymentMethod),{origin:window.location.origin}))},browser_info:ss(),vault_payment_instrument:o||null,set_as_default_stored_instrument:a||null}}})}catch(e){yield this._processAdditionalAction(e,o,a)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._componentState=void 0,this._paymentComponent&&(this._paymentComponent.unmount(),this._paymentComponent=void 0),this._cardVerificationComponent&&(this._cardVerificationComponent.unmount(),this._cardVerificationComponent=void 0),Promise.resolve()}_getAdyenClient(){if(!this._adyenClient)throw new ri(ti.PaymentNotInitialized);return this._adyenClient}_getPaymentInitializeOptions(){if(!this._paymentInitializeOptions)throw new vi('"options.adyenv2" argument was not provided during initialization.');return this._paymentInitializeOptions}_getThreeDS2ChallengeWidgetSize(){const{additionalActionOptions:e,threeDS2Options:t}=this._getPaymentInitializeOptions();return e.widgetSize||(null==t?void 0:t.widgetSize)||"05"}_handleAction(e){return new Promise((t,n)=>{const{threeDS2ContainerId:i,additionalActionOptions:r}=this._getPaymentInitializeOptions(),{onBeforeLoad:o,containerId:a,onLoad:s,onComplete:d}=r,c=JSON.parse(e.action),l=this._getAdyenClient().createFromAction(c,{onAdditionalDetails:e=>{const n={methodId:c.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};d&&d(),t(n)},size:this._getThreeDS2ChallengeWidgetSize(),onError:e=>n(e)});o&&o(c.type===Ed.ThreeDS2Challenge||c.type===Ed.QRCode),l.mount(`#${a||i}`),s&&s(()=>{n(new Wi),l.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let n;return new Promise((i,r)=>{var o,a,s;if(e.cardVerificationContainerId){n=t.create(Ad.SecuredFields,Object.assign(Object.assign({},e.options),{styles:Object.assign(Object.assign({},null===(o=e.options)||void 0===o?void 0:o.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(s=null===(a=e.options)||void 0===a?void 0:a.styles)||void 0===s?void 0:s.placeholder)}),onChange:e=>this._updateComponentState(e),onError:t=>e.validateCardFields(t),onFieldValid:t=>e.validateCardFields(t)}));try{n.mount(`#${e.cardVerificationContainerId}`)}catch(e){r(new ri(ti.PaymentNotInitialized))}}i(n)})}_mountPaymentComponent(e){let t;const n=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((r,o)=>{switch(e.method){case Td.CreditCard:case Td.ACH:case Td.Bancontact:{const r=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:a}=e.initializationData;t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e),data:this._mapAdyenPlaceholderData(r,a)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ti.PaymentNotInitialized))}break}case Td.IDEAL:case Td.SEPA:if(n.hasVaultedInstruments)this._updateComponentState({data:{paymentMethod:{type:e.method}}});else{t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ti.PaymentNotInitialized))}}break;case Td.AliPay:case Td.GiroPay:case Td.Sofort:case Td.Klarna:case Td.KlarnaPayNow:case Td.KlarnaAccount:case Td.Vipps:case Td.WeChatPayQR:this._updateComponentState({data:{paymentMethod:{type:e.method}}})}r(t)})}_processAdditionalAction(e,t,n){return Rd(this,void 0,void 0,function*(){if(!pa(e)||!fe(e.body.errors,{code:"additional_action_required"}))throw e;const i=yield this._handleAction(e.body.provider_data);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},i.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n})}))}catch(e){return this._processAdditionalAction(e,t,n)}})}_updateComponentState(e){this._componentState=e}_validateCardData(){var e,t;const n=this._getPaymentInitializeOptions().hasVaultedInstruments?this._cardVerificationComponent:this._paymentComponent;if((null===(e=null==n?void 0:n.componentRef)||void 0===e?void 0:e.showValidation)&&n.state&&(n.componentRef.showValidation(),0===Object.keys(n.state).length||!n.state.isValid&&!n.state.issuer||"sepadirectdebit"===(null===(t=n.props)||void 0===t?void 0:t.type)&&n.state.data&&Object.values(n.state.data).some(e=>0===e.toString().trim().length)))throw new lo(this._mapCardErrors(n.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}}const Ld=fi(e=>new Fd(e,new zd(a(),s())),[{gateway:"adyenv2"}]);class jd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-5MvB4RnzvviA3VBT4KYABZ4HXNZG5LRqREEgd41xt/pf/QvKmsj2O9GuNuywRXx9",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return yield this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function Bd(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}var Ud=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return Ud(this,void 0,void 0,function*(){const{adyenv3:t}=e;if(!t)throw new vi('Unable to initialize payment because "options.adyenv3" argument is not provided.');this._paymentInitializeOptions=t;const n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{environment:i,clientKey:r,paymentMethodsResponse:o,installmentOptions:a}=n.initializationData||{};return this._adyenClient=yield this._scriptLoader.load({paymentMethodsConfiguration:Object.assign({klarna:{useKlarnaWidget:!0},klarna_account:{useKlarnaWidget:!0},klarna_paynow:{useKlarnaWidget:!0}},a?{card:{installmentOptions:Object.assign({showInstallmentAmounts:!0},a)}}:{}),environment:i,locale:this._getLocale(),clientKey:r,paymentMethodsResponse:o,showPayButton:!1,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this._paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){var n;return Ud(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!i)throw new co(["payment"]);const o=i.paymentData,{shouldSaveInstrument:a,shouldSetAsDefaultInstrument:s}=Bd(o)?o:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};this._validateCardData(),"klarna"!==i.methodId&&"klarna_account"!==i.methodId&&"klarna_paynow"!==i.methodId||null===(n=this._paymentComponent)||void 0===n||n.submit(),yield this._paymentIntegrationService.submitOrder(r,t);const d=this._componentState||{data:{paymentMethod:{type:i.methodId}}};if(o&&Nd(o)){let e={};if(xd(d)){const{encryptedCardNumber:t,encryptedSecurityCode:n,encryptedExpiryMonth:i,encryptedExpiryYear:r}=d.data.paymentMethod;e={credit_card_number_confirmation:t,expiry_month:i,expiry_year:r,verification_value:n}}try{return void(yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:{formattedPayload:{bigpay_token:Object.assign(Object.assign({},e),{token:o.instrumentId}),origin:window.location.origin,browser_info:ss(),set_as_default_stored_instrument:s||null}}})))}catch(t){return void(yield this._processAdditionalAction(t,a,s,o.instrumentId,e))}}let c=JSON.stringify(Object.assign(Object.assign({},d.data.paymentMethod),{type:i.methodId,origin:window.location.origin}));"boletobancario"===i.methodId&&function(e){var t,n;return"string"===("object"==typeof e&&typeof e.data.socialSecurityNumber)&&"string"==typeof(null===(t=e.data.shopperName)||void 0===t?void 0:t.firstName)&&"string"==typeof(null===(n=e.data.shopperName)||void 0===n?void 0:n.lastName)}(d)&&(c=JSON.stringify(Object.assign(Object.assign({socialSecurityNumber:d.data.socialSecurityNumber},d.data.shopperName),{type:i.methodId,origin:window.location.origin})));try{yield this._paymentIntegrationService.submitPayment({methodId:i.methodId,paymentData:{formattedPayload:Object.assign(Object.assign({credit_card_token:{token:c}},xd(d)&&d.data.installments?{installments:{value:d.data.installments.value,plan:d.data.installments.plan||"regular"}}:{}),{browser_info:ss(),vault_payment_instrument:a||null,set_as_default_stored_instrument:s||null})}})}catch(e){yield this._processAdditionalAction(e,a,s)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._componentState=void 0,this._paymentComponent&&(this._paymentComponent.unmount(),this._paymentComponent=void 0),this._cardVerificationComponent&&(this._cardVerificationComponent.unmount(),this._cardVerificationComponent=void 0),Promise.resolve()}_updateComponentState(e){this._componentState=e}_getLocale(){const e=this._paymentIntegrationService.getState().getLocale();return e&&"es"===e.substring(0,2)?"es":e}_getAdyenClient(){if(!this._adyenClient)throw new ri(ti.PaymentNotInitialized);return this._adyenClient}_getPaymentInitializeOptions(){if(!this._paymentInitializeOptions)throw new vi('"options.adyenv3" argument was not provided during initialization.');return this._paymentInitializeOptions}_handleAction(e){return new Promise((t,n)=>{const{additionalActionOptions:i}=this._getPaymentInitializeOptions(),{onBeforeLoad:r,containerId:o,onLoad:a,onComplete:s,widgetSize:d,onActionHandled:c}=i,l=JSON.parse(e.action),u=this._getAdyenClient().createFromAction(l,{onActionHandled:e=>{c&&"function"==typeof c&&"3DS2Fingerprint"!==e.componentType&&c()},onAdditionalDetails:e=>{const n={methodId:l.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};s&&"function"==typeof s&&s(),t(n)},challengeWindowSize:d||"05",onError:e=>n(e)});r&&"function"==typeof r&&r(l.type===Od.ThreeDS2||l.type===Od.QRCode||l.type===Od.Sdk),this._mountElement(u,o),a&&"function"==typeof a&&a(()=>{n(new Wi),u.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",firstName:t?n:"",lastName:t?i:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let n;return new Promise((i,r)=>{var o,a,s;if(e.cardVerificationContainerId){n=t.create(Ad.SecuredFields,Object.assign(Object.assign({},e.options),{styles:Object.assign(Object.assign({},null===(o=e.options)||void 0===o?void 0:o.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(s=null===(a=e.options)||void 0===a?void 0:a.styles)||void 0===s?void 0:s.placeholder)}),onChange:e=>this._updateComponentState(e),onError:t=>e.validateCardFields(t),onFieldValid:t=>e.validateCardFields(t)}));try{this._mountElement(n,e.cardVerificationContainerId)}catch(e){r(new ri(ti.PaymentNotInitialized))}}i(n)})}_mountPaymentComponent(e){let t;const n=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((r,o)=>{const a=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:s}=e.initializationData;t=i.create(e.method,Object.assign(Object.assign(Object.assign({},n.options),{showBrandsUnderCardNumber:!1,billingAddressRequired:!1,showEmailAddress:!1,onChange:e=>this._updateComponentState(e),onSubmit:e=>this._updateComponentState(e)}),a?{data:this._mapAdyenPlaceholderData(a,s)}:{}));try{this._mountElement(t,n.containerId)}catch(e){o(new ri(ti.PaymentNotInitialized))}r(t)})}_processAdditionalAction(e,t,n,i,r){return Ud(this,void 0,void 0,function*(){if(!pa(e)||!fe(e.body.errors,{code:"additional_action_required"}))throw e;const o=yield this._handleAction(e.body.provider_data);try{const e=Object.assign(Object.assign({},o.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n}),a=n&&!t?{instrumentId:i,formattedPayload:{bigpay_token:Object.assign(Object.assign({},r),{token:i})}}:{};yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},o),{paymentData:Object.assign(Object.assign({},e),a)}))}catch(e){return this._processAdditionalAction(e,t,n,i,r)}})}_validateCardData(){var e;const t=this._getPaymentInitializeOptions().hasVaultedInstruments?this._cardVerificationComponent:this._paymentComponent;if((null===(e=null==t?void 0:t.componentRef)||void 0===e?void 0:e.showValidation)&&t.state&&(t.componentRef.showValidation(),0===Object.keys(t.state).length||!t.state.isValid))throw new lo(this._mapCardErrors(t.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}_mountElement(e,t){document.getElementById(t)&&e.mount(`#${t}`)}}const Vd=fi(e=>new qd(e,new jd(a(),s())),[{gateway:"adyenv3"}]);var Gd,Hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wd{constructor(e,t){this.paymentIntegrationService=e,this.affirmScriptLoader=t}initialize(e){return Hd(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e.methodId);const t=this.paymentIntegrationService.getState(),{clientToken:n,config:{testMode:i}}=t.getPaymentMethodOrThrow(e.methodId);if(!n)throw new ni(ei.MissingPaymentMethod);this.affirm=yield this.affirmScriptLoader.load(n,i)})}execute(e,t){var n;return Hd(this,void 0,void 0,function*(){const i=null===(n=e.payment)||void 0===n?void 0:n.methodId,{useStoreCredit:r}=e;if(!this.affirm)throw new ri(ti.PaymentNotInitialized);if(!i)throw new co(["payment.methodId"]);yield this.paymentIntegrationService.submitOrder({useStoreCredit:r},t);const o={methodId:i,paymentData:{nonce:(yield this.initializeAffirmCheckout()).checkout_token}};yield this.paymentIntegrationService.submitPayment(o)})}deinitialize(){return this.affirm&&(this.affirm=void 0),Promise.resolve()}finalize(){return Promise.reject(new Cd)}initializeAffirmCheckout(){var e;return null===(e=this.affirm)||void 0===e||e.checkout(this.getCheckoutInformation()),new Promise((e,t)=>{var n,i;null===(n=this.affirm)||void 0===n||n.checkout.open({onFail:e=>{"canceled"===e.reason?t(new Wi):t(new Xr)},onSuccess:t=>{e(t)}}),null===(i=this.affirm)||void 0===i||i.ui.error.on("close",()=>{t(new Wi)})})}getCheckoutInformation(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfig(),n=e.getConsignments(),i=e.getOrder(),r=e.getCart();if(!t)throw new ni(ei.MissingCheckoutConfig);if(!i)throw new ni(ei.MissingCheckout);const o=new vd(i.currency.decimalPlaces),a=this.getBillingAddress(),s=this.getShippingAddress(),d=Bo(r,t)&&s?s:a;return{merchant:{user_confirmation_url:t.links.checkoutLink,user_cancel_url:t.links.checkoutLink,user_confirmation_url_action:"POST"},shipping:d,billing:a,items:this.getItems(o,i),metadata:{shipping_type:this.getShippingType(n),mode:"modal",platform_type:"BigCommerce",platform_version:"",platform_affirm:""},discounts:this.getDiscounts(o,i),order_id:i.orderId?i.orderId.toString():"",shipping_amount:o.toInteger(i.shippingCostTotal),tax_amount:o.toInteger(i.taxTotal),total:o.toInteger(i.orderAmount)}}getShippingType(e){if(!e)return"";const t=e[0];return(null==t?void 0:t.selectedShippingOption)?t.selectedShippingOption.type:""}getBillingAddress(){const e=this.paymentIntegrationService.getState().getBillingAddress();if(!e)throw new ni(ei.MissingBillingAddress);return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone,email:e.email}}getShippingAddress(){const e=this.paymentIntegrationService.getState().getShippingAddress();if(e)return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone}}getItems(e,t){const n=[];return t.lineItems.physicalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.digitalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.giftCertificates.forEach(t=>{n.push({display_name:t.name,sku:"",unit_price:e.toInteger(t.amount),qty:1,item_image_url:"",item_url:""})}),t.lineItems.customItems&&t.lineItems.customItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.listPrice),qty:t.quantity,item_image_url:"",item_url:""})}),n}getDiscounts(e,t){const n={};return t.coupons.forEach(t=>{t.discountedAmount>0&&(n[t.code]={discount_amount:e.toInteger(t.discountedAmount),discount_display_name:t.displayName})}),t.discountAmount>0&&(n.DISCOUNTED_AMOUNT={discount_amount:e.toInteger(t.discountAmount),discount_display_name:"discount"}),n}getCategories(e){return e?e.map(e=>e.map(e=>e.name)):[[]]}}!function(e){e.PROD="//cdn1.affirm.com/js/v2/affirm.js",e.SANDBOX="//cdn1-sandbox.affirm.com/js/v2/affirm.js"}(Gd||(Gd={}));class $d{constructor(e=window){this.affirmWindow=e}load(e="",t){const n=t?Gd.SANDBOX:Gd.PROD;if(function(e,t,n,i,r,o,a){const s=e[n]||{},d=document.createElement(o),c=document.getElementsByTagName(o)[0],l=function(e,t,n){return function(){e[t]._.push([n,arguments])}};s[i]=l(s,i,"set");const u=s[i];s[r]={},s[r]._=[],u._=[],s._=[],s[r][a]=l(s,r,a),s.jsReady=function(){s._.push([a,arguments])};let h=0;for(const e="set add save post open empty reset on off trigger ready setProduct".split(" ");h<e.length;h++)u[e[h]]=l(s,i,e[h]);let p=0;for(const e=["get","token","url","items"];p<e.length;p++)u[e[p]]=function(){};d.async=!0,d.src=t[o],c.parentNode&&c.parentNode.insertBefore(d,c),delete t[o],u(t),e[n]=s}(window,{public_api_key:e,script:n},"affirm","checkout","ui","script","ready"),!this.affirmWindow.affirm)throw new mi;return Promise.resolve(this.affirmWindow.affirm)}}const Yd=fi(e=>new Wd(e,new $d),[{id:"affirm"}]);class Kd extends Xn{constructor(e){super(e||"The current order could not be finalized successfully"),this.name="OrderFinalizationNotCompletedError",this.type="order_finalization_not_completed"}}var Jd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zd{constructor(e,t){this._paymentIntegrationService=e,this._afterpayScriptLoader=t}initialize(e){var t;return Jd(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethod(e.methodId,e.gatewayId),r=(null===(t=n.getCart())||void 0===t?void 0:t.currency.code)||"",o=this._mapCurrencyToISO2(r),a=Ci(n.getStoreConfigOrThrow().checkoutSettings.features,"PI-4789.afterpay_script_use_https",!1);if(!i)throw new ni(ei.MissingPaymentMethod);this._afterpaySdk=yield this._afterpayScriptLoader.load(i,o,a)})}deinitialize(){return this._afterpaySdk&&(this._afterpaySdk=void 0),Promise.resolve()}execute(e,t){var n;return Jd(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment.gatewayId","payment.methodId"]);const{gatewayId:i,methodId:r}=e.payment;if(!i||!r)throw new co(["payment.gatewayId","payment.methodId"]);const{useStoreCredit:o}=e;void 0!==o&&(yield this._paymentIntegrationService.applyStoreCredit(o)),yield this._loadPaymentMethod(i,r,t);const a=this._paymentIntegrationService.getState();yield this._paymentIntegrationService.validateCheckout(a.getCheckout(),t);const s=(null===(n=a.getCart())||void 0===n?void 0:n.currency.code)||"",d=this._mapCurrencyToISO2(s);return this._redirectToAfterpay(d,a.getPaymentMethod(r,i)),new Promise(()=>{})})}finalize(e){var t,n,i;return Jd(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ni(ei.MissingCheckout);if(!(null==a?void 0:a.payment.token))throw new ni(ei.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToAfterpay(e,t){if(!this._afterpaySdk||!(null==t?void 0:t.clientToken))throw new ri(ti.PaymentNotInitialized);this._afterpaySdk.initialize({countryCode:e}),this._afterpaySdk.redirect({token:t.clientToken})}_mapCurrencyToISO2(e){return{AUD:"AU",NZD:"NZ",CAD:"CA",USD:"US"}[e]||"AU"}_loadPaymentMethod(e,t,n){var i;return Jd(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new vi("Afterpay can't process your payment for this order, please try another payment method");throw e}})}}var Qd,Xd;!function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Qd||(Qd={})),function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Xd||(Xd={}));class ec{constructor(e){this._scriptLoader=e}load(e,t,n=!1){return i=this,r=void 0,a=function*(){const i=e.config.testMode||!1,r=this._getScriptURI(t,i,n);return this._scriptLoader.loadScript(r).then(()=>{if(!function(e){return"AfterPay"in e}(window))throw new mi;return window.AfterPay})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}_getScriptURI(e,t,n=!1){return"US"===e?n?t?Xd.HTTPS_SANDBOX:Xd.HTTPS_PROD:t?Xd.SANDBOX:Xd.PROD:n?t?Qd.HTTPS_SANDBOX:Qd.HTTPS_PROD:t?Qd.SANDBOX:Qd.PROD}}const tc=fi(e=>new Zd(e,new ec(o())),[{gateway:"afterpay"},{id:"afterpay"}]);var nc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ic{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return nc(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t)throw new vi('Unable to proceed because "methodId" argument is not provided.');const i=this.paymentIntegrationService.getState(),{features:r}=i.getStoreConfigOrThrow().checkoutSettings,o=i.getPaymentMethodOrThrow(t),a=o.initializationData||{},{paymentToken:s="",region:d="",isButtonMicroTextDisabled:c}=a;if(yield this.amazonPayV2PaymentProcessor.initialize(o),this._isReadyToPay(s))(null==n?void 0:n.editButtonId)&&this._bindEditButton(n.editButtonId,s,"changePayment",this._isModalFlow(d));else{const{id:e}=this._createContainer();if(this._amazonPayButton=this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:i,containerId:e,decoupleCheckoutInitiation:this._isOneTimeTransaction(r,d.toUpperCase()),methodId:t,placement:si.Checkout,isButtonMicroTextDisabled:c}),!this._amazonPayButton)throw new vi("Unable to render the Amazon Pay button to an invalid HTML container element.")}})}execute(e,t){return nc(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);const{methodId:i}=n,r=this.paymentIntegrationService.getState(),{features:o}=r.getStoreConfigOrThrow().checkoutSettings,a=r.getPaymentMethodOrThrow(i).initializationData||{},{paymentToken:s="",region:d=""}=a;if(this._isReadyToPay(s)||this._isOneTimeTransaction(o,d.toUpperCase())){const n={methodId:i,paymentData:{nonce:s||"apb"}};yield this.paymentIntegrationService.submitOrder(e,t);try{return void(yield this.paymentIntegrationService.submitPayment(n))}catch(e){if(!(pa(e)&&(c=e.body,"object"==typeof c&&null!==c&&"status"in c&&"additional_action_required"in c&&"additional_action_required"===c.status&&"data"in c.additional_action_required&&"redirect_url"in c.additional_action_required.data&&"string"==typeof c.additional_action_required.data.redirect_url)))throw e;const{additional_action_required:t}=e.body,{redirect_url:n}=t.data;if(s)return new Promise(()=>window.location.assign(n));this.amazonPayV2PaymentProcessor.prepareCheckout(JSON.parse(n))}}var c;return this._getAmazonPayButton().click(),this._isModalFlow(d)?new Promise((e,t)=>{const n=()=>{window.removeEventListener("focus",n),t(new Wi("Shopper needs to login to Amazonpay to continue"))};window.addEventListener("focus",n)}):new Promise(ce)})}finalize(){return Promise.reject(new Cd)}deinitialize(){return nc(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize(),this._amazonPayButton=void 0})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(!i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>{this._showLoadingSpinner()})}this.amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_isModalFlow(e){return"us"===e}_showLoadingSpinner(){return nc(this,void 0,void 0,function*(){yield this.paymentIntegrationService.widgetInteraction(()=>new Promise(ce))})}_createContainer(){let e=document.getElementById("AmazonPayButton");return e||(e=document.createElement("div"),e.id="AmazonPayButton",e.style.display="none",document.body.appendChild(e))}_getAmazonPayButton(){return ii(this._amazonPayButton,()=>new ri(ti.PaymentNotInitialized))}_isOneTimeTransaction(e,t){return this.amazonPayV2PaymentProcessor.isPh4Enabled(e,t)&&e["INT-6399.amazon_pay_apb"]}_isReadyToPay(e){return!!e}}const rc=fi(e=>new ic(e,gi()),[{id:"amazonpay"}]);var oc,ac=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Shipping="Shipping",e.Subtotal="Subtotal",e.StoreCredit="Store Credit"}(oc||(oc={}));class sc{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._shippingLabel=oc.Shipping,this._subTotalLabel=oc.Subtotal,this._storeCreditLabel=oc.StoreCredit}initialize(e){var t,n,i,r;return ac(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new vi('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:o}=e;yield this._applePayScriptLoader.loadSdk(),this._shippingLabel=(null===(t=e.applepay)||void 0===t?void 0:t.shippingLabel)||oc.Shipping,this._subTotalLabel=(null===(n=e.applepay)||void 0===n?void 0:n.subtotalLabel)||oc.Subtotal,this._storeCreditLabel=(null===(i=e.applepay)||void 0===i?void 0:i.storeCreditLabel)||oc.StoreCredit;const a=(yield this._paymentIntegrationService.loadPaymentMethod(o)).getPaymentMethodOrThrow(o);(null===(r=a.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&a.clientToken&&this._braintreeSdk.initialize(a.clientToken)})}execute(e,t){return ac(this,void 0,void 0,function*(){const{payment:n}=e,i=this._paymentIntegrationService.getState();if(!n)throw new co(["payment"]);const{methodId:r}=n,o=i.getPaymentMethodOrThrow(r),a=this._getBaseRequest(i,o),s=this._sessionFactory.create(a);return yield this._paymentIntegrationService.submitOrder({useStoreCredit:e.useStoreCredit},t),s.begin(),new Promise((e,t)=>{this._handleApplePayEvents(s,o,{resolve:e,reject:t})})})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_getBaseRequest(e,t){const n=e.getCheckoutOrThrow(),i=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),{storeProfile:{storeCountryCode:o,storeName:a}}=r,{currency:{code:s,decimalPlaces:d}}=i,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=t,{grandTotal:u,isStoreCreditApplied:h,outstandingBalance:p}=n,m=[{label:this._subTotalLabel,amount:`${n.subtotal.toFixed(d)}`}];if(n.taxes.forEach(e=>m.push({label:e.name,amount:`${e.amount.toFixed(d)}`})),m.push({label:this._shippingLabel,amount:`${n.shippingCostTotal.toFixed(d)}`}),h){const{storeCredit:t}=e.getCustomerOrThrow();m.push({label:this._storeCreditLabel,amount:`-${Math.min(u,t).toFixed(d)}`})}return{countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:m,total:{label:a,amount:`${p.toFixed(d)}`,type:"final"}}}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>ac(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){throw new Error("Merchant validation failed")}}),e.oncancel=()=>ac(this,void 0,void 0,function*(){return n.reject(new Wi("Continue with applepay"))}),e.onpaymentauthorized=i=>this._onPaymentAuthorized(i,e,t,n)}_onValidateMerchant(e,t){return ac(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/api/public/v1/payments/applepay/validate_merchant`,{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})})}_onPaymentAuthorized(e,t,n,i){var r;return ac(this,void 0,void 0,function*(){const{token:o}=e.payment;let a;(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&(a=yield this._getBraintreeDeviceData());const s={methodId:n.id,paymentData:{deviceSessionId:a,formattedPayload:{apple_pay_token:{payment_data:o.paymentData,payment_method:o.paymentMethod,transaction_id:o.transactionIdentifier}}}};try{return yield this._paymentIntegrationService.submitPayment(s),t.completePayment(ApplePaySession.STATUS_SUCCESS),i.resolve()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),i.reject(new ri(ti.PaymentNotInitialized))}})}_getBraintreeDeviceData(){return ac(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const dc=fi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new sc(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]),cc={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},lc=function({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};function uc(e){return"object"==typeof e&&null!==e&&"bigpayToken"in e&&"defaultInstrument"in e&&"provider"in e&&"trustedShippingAddress"in e&&"method"in e&&"type"in e}var hc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.paypalSdkHelper=n,this.loadingIndicator=i}initialize(e){return hc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments:n}=e||{};if(this.bigcommerce_payments=n,!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new vi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{container:o,bannerContainerId:a}=n,{orderId:s,paypalBNPLConfiguration:d=[],isPayPalCreditAvailable:c}=r.initializationData||{};if(void 0!==a){if(!document.getElementById(a))return void console.error("Unable to create banner without valid banner container ID.");const e=null==d?void 0:d.find(({id:e})=>"checkout"===e);if(c||!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,a,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}s?this.orderId=s:(this.loadingIndicatorContainer=null==o?void 0:o.split("#")[1],yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),n.onInit&&"function"==typeof n.onInit&&n.onInit(()=>this.renderButton(t,n)),(void 0===n.shouldRenderPayPalButtonOnInitialization||n.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(t,n))})}execute(e,t){return hc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{onError:r}=this.bigcommerce_payments||{};if(!n)throw new co(["payment"]);const{methodId:o,paymentData:a}=n;if(this.isPayPalVaultedInstrumentPaymentData(a)&&!this.orderId&&(this.orderId=yield this.createOrder()),!this.orderId)throw new Xr;const s=this.isPayPalVaultedInstrumentPaymentData(a)?this.prepareVaultedInstrumentPaymentPayload(o,this.orderId,a):this.preparePaymentPayload(o,this.orderId,a);try{yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment(s)}catch(e){return this.isProviderError(e)&&(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n.methodId),yield new Promise((e,t)=>{var i;this.bigcommerce_payments&&(null===(i=this.paypalButton)||void 0===i||i.close(),this.renderButton(n.methodId,this.bigcommerce_payments),this.handleError(new Error("INSTRUMENT_DECLINED"),r)),t()})),this.handleError(e,r),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=Bd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new vi('Unable to initialize payment because "container" argument is not provided.');const y=Object.assign(Object.assign({},this.isAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(y),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return hc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return hc(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_paymentscheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.bigcommerce_payments||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&Nd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&Nd(e)&&Bd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isAppSwitchEnabled(e){var t,n;return null!==(n=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==n&&n}}const mc=fi(e=>new pc(e,Sr(e),Rr(),new fd({containerStyles:cc})),[{id:"bigcommerce_payments"}]);function yc(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var gc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsRequestSender=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){var t,n;return gc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_fastlane:r}=e;if(!i)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(this.methodId=i,!r)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_fastlane" argument is not provided.');if(this.bigcommerce_payments_fastlane=r,!r.onInit||"function"!=typeof r.onInit)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(s,a.currency.code,a.id);const l=qr(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return gc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{paymentData:r,methodId:o}=n,a=r&&Nd(r);try{yield this.paymentIntegrationService.submitOrder(i,t);const e=a?yield this.prepareVaultedInstrumentPaymentPayload(o,r):yield this.preparePaymentPayload(o,r);yield this.paymentIntegrationService.submitPayment(e),this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId()}catch(e){if(function(e){return"object"==typeof e&&null!==e&&"message"in e&&"response"in e&&"name"in e.response}(e)&&"INVALID_REQUEST"===e.response.name){const e={translationKey:"payment.errors.invalid_request_error"};return this.handleError(e),Promise.reject()}if(e instanceof Error&&"FastlaneError"!==e.name)throw e;return Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return gc(this,void 0,void 0,function*(){return Promise.resolve()})}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getCustomerOrThrow(),i=e.getPaymentProviderCustomer(),r=yc(i)?i:{},o=this.bigCommercePaymentsFastlaneUtils.getStorageSessionId();return!(!n.isGuest||(null==r?void 0:r.authenticationState)===zr.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}runPayPalAuthenticationFlowOrThrow(e){return gc(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),{authenticationState:d,addresses:c,instruments:l}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,s);yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:d,addresses:c,instruments:l}),s.authenticationState===zr.CANCELED?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(n.id)}catch(e){}})}initializePayPalPaymentComponent(){return gc(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),t=e.phone,n=`${e.firstName} ${e.lastName}`.trim(),i=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),r={fields:Object.assign({cardholderName:{prefill:n,enabled:!0}},t&&{phoneNumber:{prefill:t}})};this.paypalComponentMethods=yield i.FastlaneCardComponent(r)})}renderPayPalPaymentComponent(e){const t=this.getPayPalComponentMethodsOrThrow();if(!e)throw new vi('Unable to render card component because "container" argument is not provided.');t.render(e)}getPayPalComponentMethodsOrThrow(){if(!this.paypalComponentMethods)throw new mi;return this.paypalComponentMethods}prepareVaultedInstrumentPaymentPayload(e,t){return gc(this,void 0,void 0,function*(){const{instrumentId:n}=t,i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),r=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&i.config.is3dsEnabled?yield this.get3DSNonce(n):n;return yield this.createOrder(r),{methodId:e,paymentData:{formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:r}}}}})}preparePaymentPayload(e,t){return gc(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getBillingAddressOrThrow(),r=n.getPaymentMethodOrThrow(e),o=`${i.firstName} ${i.lastName}`.trim(),{getPaymentToken:a}=this.getPayPalComponentMethodsOrThrow(),{id:s}=yield a({name:{fullName:o},billingAddress:this.bigCommercePaymentsFastlaneUtils.mapBcToPayPalAddress(i)}),d=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&r.config.is3dsEnabled,{shouldSaveInstrument:c=!1,shouldSetAsDefaultInstrument:l=!1}=Bd(t)?t:{},u=d?yield this.get3DSNonce(s):s;return yield this.createOrder(u),{methodId:e,paymentData:Object.assign(Object.assign({},t),{shouldSaveInstrument:c,shouldSetAsDefaultInstrument:l,formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:u}}})}})}createOrder(e){return gc(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getCartOrThrow().id;if(this.methodId){const{orderId:n}=yield this.bigCommercePaymentsRequestSender.createOrder(this.methodId,{cartId:t,fastlaneToken:e});this.orderId=n}})}get3DSNonce(e){var t;return gc(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getCartOrThrow(),r=n.getOrderOrThrow(),o=n.getStoreConfigOrThrow().links.checkoutLink,a=null===(t=this.paypalFastlaneSdk)||void 0===t?void 0:t.ThreeDomainSecureClient;if(!a)throw new mi;const s={amount:r.orderAmount.toFixed(2),currency:i.currency.code,nonce:e,threeDSRequested:this.threeDSVerificationMethod===Ar.Always,transactionContext:{experience_context:{locale:"en-US",return_url:o,cancel_url:o}}},d=yield a.isEligible(s);if(this.threeDSVerificationMethod===Ar.Always&&!d)throw new Xr;if(d){const{liabilityShift:e,authenticationState:t,nonce:n}=yield a.show();if(e===ir.No||e===ir.Unknown||t===Tr.Errored||t===Tr.Cancelled)throw new Xr;if(t===Tr.Succeeded&&[ir.Yes,ir.Possible].includes(e))return n}return e})}handlePayPalStoredInstrumentChange(e){return gc(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:n,selectedCard:i}=yield t.profile.showCardSelector();if(n){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),n=yc(t)?t:{},r=this.bigCommercePaymentsFastlaneUtils.mapPayPalToBcInstrument(e,i)[0];return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},n),{instruments:[r]})),r}})}isBigcommercePaymentsFastlaneThreeDSAvailable(){return Ci(this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.bcp_fastlane_three_ds")}handleError(e){var t;(null===(t=this.bigcommerce_payments_fastlane)||void 0===t?void 0:t.onError)&&"function"==typeof this.bigcommerce_payments_fastlane.onError&&this.bigcommerce_payments_fastlane.onError(e)}}const vc=fi(e=>{const{getHost:t}=e.getState();return new fc(e,new fr(n({host:t()})),Rr(),Br())},[{id:"bigcommerce_payments_fastlane"}]);var _c=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.paypalSdkHelper=i}initialize(e){return _c(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_paylater:n}=e||{};if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:o=[],orderId:a}=r.initializationData||{},{bannerContainerId:s,container:d}=n;if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=o&&o.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return this.renderMessages(t,s,e)}a?this.orderId=a:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==d?void 0:d.split("#")[1],this.renderButton(t,n))})}execute(e,t){return _c(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);if(!this.orderId)throw new Xr;yield this.paymentIntegrationService.submitOrder(i,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(n.methodId,this.orderId)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.bigCommercePaymentsButtons)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){if(!(null==t?void 0:t.container))throw new vi('Unable to initialize payment because "container" argument is not provided.');const n=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=i.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u=[n.FUNDING.PAYLATER,n.FUNDING.CREDIT];let h=!1;u.forEach(e=>{if(h)return;const t={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.bigCommercePaymentsButtons=n.Buttons(t),this.bigCommercePaymentsButtons.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.bigCommercePaymentsButtons.isEligible()&&e===n.FUNDING.CREDIT)throw new _i(`BigCommercePayments ${e} is not available for your region. Please use BigCommercePayments Checkout instead.`);d&&"function"==typeof d&&d(),this.bigCommercePaymentsButtons.render(a),h=!0}})}handleClick(e,t){return _c(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;t&&"function"==typeof t&&(yield t(()=>(this.toggleLoadingIndicator(!0),n()),i))})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}}const Ic=fi(e=>new Sc(e,Sr(e),new fd({containerStyles:cc}),Rr()),[{id:"bigcommerce_payments_paylater"}]);class wc extends nr{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var Cc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class bc{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return Cc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_ratepay:i}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_ratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new vi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new vi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new vi("Unable to initialize payment because merchantId argument is not provided.");this.bigcommerce_payments_ratepay=i,yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return Cc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{getFieldsValues:r}=this.bigcommerce_payments_ratepay||{};if(!n)throw new co(["payment"]);if(!r||"function"!=typeof r)throw new vi('Unable to initialize payment because "options.getFieldsValues" argument is not provided.');this.toggleLoadingIndicator(!0);try{const e=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apmscheckout",{metadataId:this.guid}),{ratepayBirthDate:o,ratepayPhoneNumber:a,ratepayPhoneCountryCode:s}=r(),d={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:n.methodId,rate_pay:{birth_date:this.normalizeDate(o),phone:{national_number:a,country_code:s.split("+")[1]}},paypal_account:{order_id:e}}};return yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:d}),yield new Promise((e,t)=>{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.bigcommerce_payments_ratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new vi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.bigcommerce_payments_ratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return Cc(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return Cc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus("bigcommerce_payments_apms",{params:{useMetadata:!0}}),o=r===cr.PollingStop,a=r===cr.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,n,i);yield this.reinitializeStrategy({methodId:e,gatewayId:i,bigcommerce_payments_ratepay:this.bigcommerce_payments_ratepay}),this.handleError(new wc)}catch(e){this.handleError(e),n()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const Pc=fi(e=>new bc(e,Sr(e),new fd({containerStyles:Object.assign(Object.assign({},cc),{position:"fixed"})})),[{gateway:"bigcommerce_payments_apms",id:"ratepay"}]);var Oc;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification",e.CardExpiryVerification="cardExpiryVerification"}(Oc||(Oc={}));const Ec=Oc;function Ac(e){return Ec.CardNumber in e&&Ec.CardName in e&&Ec.CardExpiry in e}function Tc(e){return Ec.CardNumberVerification in e&&Ec.CardCodeVerification in e&&Ec.CardExpiryVerification in e}var kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Dc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){return kc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_creditcards:n}=e,i=n,{form:r,onCreditCardFieldsRenderingError:o,onLoadComplete:a}=i||{};if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new vi('Unable to proceed because "options.bigcommerce_payments_creditcards.form" argument is not provided.');this.hostedFormOptions=r,this.isCreditCardForm=Ac(r.fields),this.isCreditCardVaultedForm=Tc(r.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(r,o)),null==a||a(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return kc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{methodId:r,paymentData:o}=n||{};if(!n||!r)throw new co(["payment"]);if(this.executionPaymentData=o,this.isCreditCardForm||this.isCreditCardVaultedForm)yield this.validateHostedFormOrThrow(),yield this.submitHostedForm();else{const{orderId:e}=yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",this.getInstrumentParams());this.returnedOrderId=e}const a=this.preparePaymentPayload(r,o,this.returnedOrderId,this.returnedVaultedToken);yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e,t,n,i;return kc(this,void 0,void 0,function*(){return yield null===(e=this.cvvField)||void 0===e?void 0:e.close(),yield null===(t=this.expiryField)||void 0===t?void 0:t.close(),yield null===(n=this.numberField)||void 0===n?void 0:n.close(),yield null===(i=this.nameField)||void 0===i?void 0:i.close(),Promise.resolve()})}preparePaymentPayload(e,t,n,i){const{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=Bd(t)?t:{},a=t&&Nd(t)?t.instrumentId:void 0,s=ue({verification_nonce:i,token:a},J);return{methodId:e,paymentData:{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o,instrumentId:a,formattedPayload:Object.assign(Object.assign({},i||a?{bigpay_token:s}:{}),n?{card_with_order:{order_id:n}}:{})}}}initializeFields(e,t){return kc(this,void 0,void 0,function*(){const{fields:n,styles:i}=e,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),o=this.getExecuteCallback(n),a=Object.assign({style:this.getInputStyles(i),onApprove:({orderID:e,vaultSetupToken:t,liabilityShift:n})=>{if(n===ir.No||n===ir.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ti.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>kc(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>kc(this,void 0,void 0,function*(){const{orderId:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return kc(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return kc(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(Bd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(Nd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return kc(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return kc(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ti.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isBigCommercePaymentsAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return kc(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(i,n.currency.code,n.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const Mc=fi(e=>new Dc(e,Sr(e),Rr(),Br()),[{id:"bigcommerce_payments_creditcards"}]);var zc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class xc{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdkHelper=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return zc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n,t),{orderId:a,shouldRenderFields:s}=o.initializationData||{},d=r.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=Ci(d,"PAYPAL-5624.bcp_ideal_polling"),a?this.orderId=a:(this.paypalApms=yield this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(o,r.getCartOrThrow().currency.code),this.loadingIndicatorContainer=i.container.split("#")[1],this.renderButton(n,t,i),s&&this.renderFields(n,i))})}execute(e,t){return zc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{methodId:r,gatewayId:o}=n;if(!this.orderId)throw new Xr;this.isPollingEnabled&&"ideal"===r&&(yield new Promise((e,t)=>{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.bigCommercePaymentsIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isPollingEnabled&&this.resetPollingMechanism(),null===(e=this.bigCommercePaymentsButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return zc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus(i),o=r===cr.Approved,a=r===cr.PollingError;if(o)return this.deInitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,n,i);yield this.reinitializeStrategy({methodId:e,gatewayId:i,bigCommercePaymentsAlternativeMethods:this.bigCommercePaymentsAlternativeMethods}),this.handleError(new wc)}catch(e){n()}})}deInitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deInitializePollingMechanism()}reinitializeStrategy(e){return zc(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderButton(e,t,n){const i=this.getPaypalAmpsSdkOrThrow(),r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t),{buttonStyle:o}=r.initializationData||{},{container:a,onError:s,onRenderButton:d,submitForm:c}=n,l={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),onInit:(e,t)=>n.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deInitializePollingMechanism()},onError:e=>{this.deInitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>zc(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.bigCommercePaymentsButton=i.Buttons(l),this.bigCommercePaymentsButton.isEligible()&&(d&&"function"==typeof d&&d(),this.bigCommercePaymentsButton.render(a))}onCreateOrder(e,t,n){return zc(this,void 0,void 0,function*(){const{onValidate:i}=n;yield i(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const r=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms");if(this.isNonInstantPaymentMethod(e)){const n={useStoreCredit:!1},i={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(n,i),yield this.bigCommercePaymentsIntegrationService.submitPayment(e,r,t)}return r})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in dr}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const Nc=fi(e=>new xc(e,Sr(e),Rr(),new fd({containerStyles:cc})),[{gateway:"bigcommerce_payments_apms"}]);class Rc{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{methodId:r,gatewayId:o}=n;try{const e={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:r,paypal_account:{order_id:yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms",{gatewayId:"bigcommerce_payments_apms",methodId:r})}}};yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment({methodId:r,gatewayId:o,paymentData:e})}catch(e){if(function(e){var t,n;return pa(e)&&(null===(n=null===(t=e.body)||void 0===t?void 0:t.additional_action_required)||void 0===n?void 0:n.data.redirect_url)}(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise((e,n)=>{window.location.replace(t),n()})}return this.handleError(e),Promise.reject(e)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};t&&"function"==typeof t&&t(e)}}const Fc=fi(e=>new Rc(e,Sr(e)),[{gateway:"bigcommerce_payments_apms",id:"klarna"},{gateway:"bigcommerce_payments_apms",id:"afterpay"}]);var Lc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class jc{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return Lc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_venmo:r}=e||{};if(!i)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=o.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=o.initializationData)||void 0===n?void 0:n.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=r.container.split("#")[1],this.renderButton(i,r))})}execute(e,t){return Lc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);if(!this.orderId)throw new Xr;yield this.paymentIntegrationService.submitOrder(i,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(n.methodId,this.orderId)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){const n=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=i.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u={fundingSource:n.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new _i("Venmo is not available for your region. Please another payment method instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return Lc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const Bc=fi(e=>new jc(e,Sr(e),new fd({styles:{backgroundColor:"black"}})),[{id:"bigcommerce_payments_venmo"}]);class Uc{initialize(e){this._blueSnapSdk=e}initialize3ds(e,t){return n=this,i=void 0,o=function*(){const n=this._getBlueSnapSdk();return new Promise((i,r)=>{n.threeDsPaymentsSetup(e,e=>"1"===e.code?i(e.threeDSecure.threeDSecureReferenceId):r(new Qr)),n.threeDsPaymentsSubmitData(t)})},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ti.PaymentNotInitialized))}}function qc(e){return Ec.CardNumber in e}function Vc(e){return Ec.CardCodeVerification in e||Ec.CardNumberVerification in e}var Gc,Hc,Wc,$c,Yc,Kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jc{constructor(e,t,n,i){this._scriptLoader=e,this._paymentIntegrationService=t,this._blueSnapDirectHostedForm=n,this._blueSnapDirect3ds=i}initialize(e){return Kc(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,creditCard:i}=e;if(!n||!i)throw new vi;const r=yield this._paymentIntegrationService.loadPaymentMethod(n,{params:{method:t,bigpayToken:i.bigpayToken}}),{config:{testMode:o,is3dsEnabled:a},clientToken:s}=r.getPaymentMethodOrThrow(t,n);this._blueSnapSdk=yield this._scriptLoader.load(o),this._paymentFieldsToken=s,this._shouldUseHostedFields=qc(i.form.fields)||Vc(i.form.fields)&&!!i.form.fields.cardNumberVerification,this._shouldUseHostedFields&&(this._blueSnapDirectHostedForm.initialize(this._blueSnapSdk,i.form.fields),yield this._blueSnapDirectHostedForm.attach(this._getPaymentFieldsToken(),i,a))})}execute(e){return Kc(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment"]);if(!this._blueSnapSdk)throw new co(["payment"]);const{paymentData:t}=e.payment,{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:i}=Bd(t)?t:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},r=this._getPaymentFieldsToken();let o;const{is3dsEnabled:a}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.payment.methodId,e.payment.gatewayId).config,s=this._shouldUseHostedFields?yield this._blueSnapDirectHostedForm.validate().submit(a?this._getBlueSnapDirectThreeDSecureData():void 0,!(Bd(t)&&Nd(t))):void 0;if(yield this._paymentIntegrationService.submitOrder(),Bd(t)&&Nd(t)&&this._paymentFieldsToken&&t.instrumentId){if(a){this._blueSnapDirect3ds.initialize(this._blueSnapSdk);const{last4:e,brand:n}=this._paymentIntegrationService.getState().getCardInstrumentOrThrow(t.instrumentId),i=Object.assign({last4Digits:e,ccType:n.toUpperCase()},this._getBlueSnapDirectThreeDSecureData());o=yield this._blueSnapDirect3ds.initialize3ds(this._paymentFieldsToken,i)}yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:Object.assign(Object.assign(Object.assign({instrumentId:t.instrumentId},this._shouldUseHostedFields?{nonce:r}:{}),o?{deviceSessionId:o}:{}),{shouldSetAsDefaultInstrument:!!i})}))}else yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify({pfToken:r,cardHolderName:s&&s.cardHolderName})},vault_payment_instrument:n,set_as_default_stored_instrument:i}}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._shouldUseHostedFields&&this._blueSnapDirectHostedForm.detach(),Promise.resolve()}_getBlueSnapDirectThreeDSecureData(){var e;const{getBillingAddress:t,getShippingAddress:n,getCustomer:i,getCheckoutOrThrow:r,getCartOrThrow:o}=this._paymentIntegrationService.getState(),a=t(),s=n(),d=(null===(e=i())||void 0===e?void 0:e.email)||(null==a?void 0:a.email),c=(null==a?void 0:a.phone)||(null==s?void 0:s.phone);return Object.assign(Object.assign(Object.assign(Object.assign({amount:r().outstandingBalance,currency:o().currency.code},d&&{email:d}),c&&{phone:c}),a&&{billingFirstName:a.firstName,billingLastName:a.lastName,billingCountry:a.countryCode,billingCity:a.city,billingAddress:`${a.address1} ${a.address2}`.trim(),billingZip:a.postalCode}),s&&{shippingFirstName:s.firstName,shippingLastName:s.lastName,shippingCountry:s.countryCode,shippingCity:s.city,shippingAddress:`${s.address1} ${s.address2}`.trim(),shippingZip:s.postalCode})}_getPaymentFieldsToken(){return ii(this._paymentFieldsToken,()=>new ni(ei.MissingPaymentToken))}}!function(e){e.AMEX="american-express",e.CHINA_UNION_PAY="unionpay",e.DINERS="diners-club",e.DISCOVER="discover",e.JCB="jcb",e.MASTERCARD="mastercard",e.UNKNOWN="unknown",e.VISA="visa"}(Gc||(Gc={})),function(e){e.ON_BLUR="onBlur",e.ON_SUBMIT="onSubmit"}(Hc||(Hc={})),function(e){e.EMPTY="empty",e.INVALID="invalid",e.THREE_DS_NOT_ENABLED="3D Secure is not enabled"}(Wc||(Wc={})),function(e){e.CC_NOT_SUPORTED="22013",e.ERROR_403="403",e.ERROR_404="404",e.ERROR_500="500",e.INVALID_OR_EMPTY="10",e.SESSION_EXPIRED="400",e.THREE_DS_AUTH_FAILED="14101",e.THREE_DS_CLIENT_ERROR="14103",e.THREE_DS_MISSING_FIELDS="14102",e.THREE_DS_NOT_ENABLED="14100",e.TOKEN_EXPIRED="14040",e.TOKEN_NOT_ASSOCIATED="14042",e.TOKEN_NOT_FOUND="14041"}($c||($c={})),function(e){e.CardCode="cvv",e.CardExpiry="exp",e.CardName="noc",e.CardNumber="ccn"}(Yc||(Yc={}));const Zc={[Yc.CardNumber]:Ec.CardNumber,[Yc.CardExpiry]:Ec.CardExpiry,[Yc.CardName]:Ec.CardName,[Yc.CardCode]:Ec.CardCode},Qc={empty:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date is required",type:"required"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV is required",type:"required"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}},invalid:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date must be a valid future date in MM / YY format",type:"invalid_card_expiry"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}}};class Xc{constructor(e,t){this._nameOnCardInput=e,this._hostedInputValidator=t}initialize(e,t){this._blueSnapSdk=e,t&&(qc(t)?this._hostedInputValidator.initialize():Vc(t)&&t.cardNumberVerification&&this._hostedInputValidator.initializeValidationFields())}attach(e,t,n){var i,r,o,a,s=t.form,{fields:d}=s,c=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(s,["fields"]);return void 0===n&&(n=!1),i=this,r=void 0,a=function*(){const t=this._getBlueSnapSdk();if(!qc(d)&&!Vc(d))throw new vi("Field options must be of type HostedCardFieldOptionsMap");return this._onValidate=c.onValidate,qc(d)&&this._setCustomBlueSnapAttributes(d),Vc(d)&&this._setCustomStoredCardsBlueSnapAttributes(d),new Promise(i=>{const r=this._getHostedPaymentFieldsOptions(e,d,c,i,n);t.hostedPaymentFieldsCreate(r),qc(d)&&this._nameOnCardInput.attach(r,d.cardName.accessibilityLabel,d.cardName.placeholder)})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}validate(){var e;const t=this._hostedInputValidator.validate();if(null===(e=this._onValidate)||void 0===e||e.call(this,t),!t.isValid){const e=Object.entries(t.errors).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n.map(({message:e,type:t})=>({message:e,type:t}))}),{});throw new lo(e)}return this}submit(e,t=!1){return new Promise((n,i)=>this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(e=>this._isBlueSnapDirectCallbackError(e)?i(new Qr(e.statusCode===$c.THREE_DS_AUTH_FAILED?e.error[0].errorDescription:`Submission failed with status: ${e.statusCode} and errors: ${JSON.stringify(e.error)}`)):n(Object.assign(Object.assign({},e.cardData),t?{cardHolderName:this._nameOnCardInput.getValue()}:{})),e))}detach(){this._nameOnCardInput.detach()}_isBlueSnapDirectCallbackError(e){return"error"in e}_getHostedPaymentFieldsOptions(e,t,{onFocus:n,onBlur:i,onValidate:r,onCardTypeChange:o,onEnter:a,styles:s},d,c){var l;return Object.assign(Object.assign(Object.assign({token:e,onFieldEventHandler:{setupComplete:()=>d(),onFocus:this._usetUiEventCallback(n),onBlur:this._usetUiEventCallback(i),onError:this._handleError(r),onType:(e,t)=>null==o?void 0:o({cardType:Gc[t]}),onEnter:this._usetUiEventCallback(a),onValid:e=>null==r?void 0:r(this._hostedInputValidator.validate({tagId:e}))}},qc(t)&&{ccnPlaceHolder:t.cardNumber.placeholder||"",cvvPlaceHolder:(null===(l=t.cardCode)||void 0===l?void 0:l.placeholder)||"",expPlaceHolder:t.cardExpiry.placeholder||"MM / YY"}),s&&{style:this._mapStyles(s)}),{"3DS":c})}_mapStyles({default:e,error:t,focus:n}){return Object.entries(Object.assign(Object.assign(Object.assign({},e&&{input:e}),t&&{".invalid":t}),n&&{":focus":n})).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:Object.entries(n).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[te(t)]:n}),{})}),{})}_handleError(e){return(t,n,i,r)=>{if(n===$c.INVALID_OR_EMPTY&&t&&function(e){return void 0!==e&&[Wc.EMPTY,Wc.INVALID].includes(e)}(i))return null==e?void 0:e(this._hostedInputValidator.validate({tagId:t,errorDescription:i}));throw new Qr(`An unexpected error has occurred: ${JSON.stringify({tagId:t,errorCode:n,errorDescription:i,eventOrigin:r})}`)}}_usetUiEventCallback(e){return t=>{e&&e({fieldType:Zc[t]})}}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ti.PaymentNotInitialized))}_setCustomBlueSnapAttributes(e){const{cardNumber:t,cardExpiry:n,cardCode:i,cardName:r}=e,o=document.getElementById(t.containerId),a=document.getElementById(n.containerId),s=i&&document.getElementById(i.containerId),d=document.getElementById(r.containerId);if(!(o&&a&&s&&d))throw new vi("Unable to create hosted payment fields to invalid HTML container elements.");o.dataset.bluesnap=Yc.CardNumber,a.dataset.bluesnap=Yc.CardExpiry,s.dataset.bluesnap=Yc.CardCode,d.dataset.bluesnap=Yc.CardName}_setCustomStoredCardsBlueSnapAttributes(e){const{cardNumberVerification:t,cardCodeVerification:n}=e,i=t&&document.getElementById(t.containerId),r=n&&document.getElementById(n.containerId);(i||r)&&(i&&(i.dataset.bluesnap=Yc.CardNumber),r&&(r.dataset.bluesnap=Yc.CardCode))}}class el{constructor(){this._errors={}}initialize(){this._errors={cardNumber:[Qc.empty.cardNumber],cardExpiry:[Qc.empty.cardExpiry],cardCode:[Qc.empty.cardCode],cardName:[Qc.empty.cardName]}}initializeValidationFields(){this._errors={cardNumberVerification:[Qc.empty.cardNumber]}}validate(e){return e&&this._updateErrors(e.tagId,e.errorDescription),{isValid:Object.values(this._errors).every(e=>0===e.length),errors:this._errors}}_updateErrors(e,t){const n=this._errors.cardNumberVerification?Ec.CardNumberVerification:Zc[e];this._errors[n]=t?[Qc[t][n]]:[]}}class tl{attach({style:e,onFieldEventHandler:{onFocus:t,onBlur:n,onValid:i,onError:r,onEnter:o}={}},a,s){var d;this._style=e,this._create(),this._getInput().addEventListener("focus",this._handleFocus(t)),this._getInput().addEventListener("blur",this._handleBlur(n,i,r)),this._getInput().addEventListener("enter",this._handleEnter(o)),a&&this._getInput().setAttribute("aria-label",a),s&&(this._getInput().placeholder=s),null===(d=document.querySelector('[data-bluesnap="noc"]'))||void 0===d||d.appendChild(this._getInput())}getValue(){return this._getInput().value}detach(){this._input&&(this._input.remove(),this._input=void 0)}_handleFocus(e){return()=>{var t;this._applyStyles(null===(t=this._style)||void 0===t?void 0:t[":focus"]),null==e||e(Yc.CardName)}}_handleBlur(e,t,n){return({target:i})=>{var r,o;null==e||e(Yc.CardName),i instanceof HTMLInputElement&&(/\w{1,200}/.test(i.value)?(this._applyStyles(null===(r=this._style)||void 0===r?void 0:r.input),null==t||t(Yc.CardName)):(this._applyStyles(null===(o=this._style)||void 0===o?void 0:o[".invalid"]),null==n||n(Yc.CardName,$c.INVALID_OR_EMPTY,Wc.EMPTY,Hc.ON_BLUR)))}}_handleEnter(e){return()=>null==e?void 0:e(Yc.CardName)}_applyStyles(e={}){const t={color:e.color,fontFamily:e["font-family"],fontSize:e["font-size"],fontWeight:e["font-weight"]},n=Object.keys(t);n.every(e=>["color","fontFamily","fontSize","fontWeight"].includes(e))&&n.forEach(e=>{t[e]&&(this._getInput().style[e]=t[e]||"")})}_configureInput(){this._getInput().autocomplete="cc-name",this._getInput().id=Yc.CardName,this._getInput().inputMode="text",this._getInput().maxLength=200,this._getInput().style.backgroundColor="transparent",this._getInput().style.border="0",this._getInput().style.height="100%",this._getInput().style.margin="0",this._getInput().style.outline="none",this._getInput().style.padding="0",this._getInput().style.width="100%",this._getInput().type="text"}_getInput(){return ii(this._input,()=>new ri(ti.PaymentNotInitialized))}_create(){var e;this._input=document.createElement("input"),this._configureInput(),this._applyStyles(null===(e=this._style)||void 0===e?void 0:e.input)}}var nl;!function(e){e.PRODUCTION="https://pay.bluesnap.com/web-sdk/5/bluesnap.js",e.SANDBOX="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"}(nl||(nl={}));class il{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e=!1){return t=this,n=void 0,r=function*(){if(this._window.bluesnap)return this._window.bluesnap;if(yield this._scriptLoader.loadScript(e?nl.SANDBOX:nl.PRODUCTION),!this._window.bluesnap)throw new mi;return this._window.bluesnap},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const rl=fi(e=>new Jc(new il(a()),e,new Xc(new tl,new el),new Uc),[{id:"credit_card",gateway:"bluesnapdirect"}]);class ol{constructor(e){this._paymentIntegrationService=e}execute(e){return t=this,n=void 0,r=function*(){const t=this._formatePaymentPayload(e);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(t)}catch(e){if(this._isBlueSnapDirectRedirectResponse(e)){const t=e.body.provider_data&&JSON.parse(e.body.provider_data);let n=e.body.additional_action_required.data.redirect_url;if(function(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!t.merchantid&&"string"==typeof t.merchantid}(t)){const e=new URLSearchParams(t).toString();n=`${n}&${e}`}return new Promise(()=>window.location.replace(n))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_formatePaymentPayload({payment:e}){if(!e)throw new co(["payment"]);return e.paymentData&&Nd(e.paymentData)&&Bd(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{instrumentId:e.paymentData.instrumentId,shouldSetAsDefaultInstrument:!!e.paymentData.shouldSetAsDefaultInstrument}}):(t=e.paymentData,Boolean("object"==typeof t&&null!==t&&"accountNumber"in t&&"accountType"in t&&"shopperPermission"in t&&"routingNumber"in t)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ecp:Object.assign({account_number:e.paymentData.accountNumber,account_type:e.paymentData.accountType,shopper_permission:e.paymentData.shopperPermission,routing_number:e.paymentData.routingNumber},e.paymentData.companyName?{company_name:e.paymentData.companyName}:{}),vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):(n=e.paymentData,Boolean("object"==typeof n&&null!==n&&"iban"in n&&"firstName"in n&&"lastName"in n&&"shopperPermission"in n)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{sepa_direct_debit:{iban:e.paymentData.iban,first_name:e.paymentData.firstName,last_name:e.paymentData.lastName,shopper_permission:e.paymentData.shopperPermission},vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"bic"in e)}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ideal:{bic:e.paymentData.bic}}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"iban"in e&&!("firstName"in e)&&!("lastName"in e)&&!("shopperPermission"in e))}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{pay_by_bank:{iban:e.paymentData.iban}}}}):{methodId:e.methodId}));var t,n}_isBlueSnapDirectRedirectResponse(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;if(!n.body)return!1;const i=n.body;return"additional_action_required"===i.status&&!!(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}}const al=fi(e=>new ol(e),[{gateway:"bluesnapdirect"}]);var sl;!function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(sl||(sl={}));const dl=sl;var cl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ll{constructor(e){this._paymentIntegrationService=e}execute(e,t){return cl(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);if(!this._initializeOptions)throw new ri(ti.PaymentNotInitialized);const{onLoad:i,style:r}=this._initializeOptions,o=this._createIframe("bluesnapv2_hosted_payment_page",r),a=new An(new Promise(ce));i(o,()=>a.cancel(new Wi)),yield this._paymentIntegrationService.submitOrder(e,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:n.methodId,gatewayId:n.gatewayId,shouldSaveInstrument:!1,target:o.name,promise:a.promise})})}finalize(e){return cl(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),n=t.getOrder(),i=t.getPaymentStatus();if(!n||i!==dl.ACKNOWLEDGE&&i!==dl.FINALIZE)return Promise.reject(new Cd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(e){return cl(this,void 0,void 0,function*(){this._initializeOptions=e&&e.bluesnapv2,yield Promise.resolve()})}deinitialize(){return Promise.resolve()}_createIframe(e,t){const n=document.createElement("iframe");if(n.setAttribute("sandbox","allow-top-navigation allow-scripts allow-forms allow-same-origin"),n.name=e,t){const{border:e,height:i,width:r}=t;n.style.border=null!=e?e:"",n.style.height=null!=i?i:"",n.style.width=null!=r?r:""}return n}}const ul=fi(e=>new ll(e),[{gateway:"bluesnapv2"}]);class hl{constructor(e){this.storage=e}saveExtraItemsData(e,t){const n=[...t.physicalItems,...t.digitalItems].reduce((e,t)=>(e[t.productId]={brand:t.brand?t.brand:"",category:t.categoryNames?t.categoryNames.join(", "):""},e),{});try{return this.storage.setItem(this.getStorageKey(e),JSON.stringify(n)),n}catch(e){return{}}}readExtraItemsData(e){try{const t=this.storage.getItem(this.getStorageKey(e));if(!t)return null;const n=JSON.parse(t);return function(e){if(!Z(e))return!1;const t=Object.values(e).some(e=>!Z(e)||!("brand"in e)||!("category"in e));return Boolean(!t)}(n)?n:null}catch(e){return null}}clearExtraItemData(e){try{this.storage.removeItem(this.getStorageKey(e))}catch(e){}}getStorageKey(e){return e?`ORDER_ITEMS_${e}`:""}}function pl(e){return Boolean(e.hasOwnProperty("analytics"))}function ml(e){return"object"==typeof e&&null!==e&&"shouldCreateAccount"in e}class yl extends Xn{constructor(e){super(),this.errorCode=e,this.name="BoltPaymentsFieldError",this.type="bolt_payments_field_error",this.body={errors:[yl.getError(e)]}}static getError(e){switch(e){case"1000":case"2000":case"3000":return{code:"invalid_number"};case"1001":case"2001":case"3001":return{code:"invalid_expiry_date"};case"1002":case"2002":return{code:"invalid_cvc"};case"1003":return{code:"invalid_zip"};case"2003":return{code:"incorrect_zip"};default:return{code:"general_error"}}}}var gl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fl{constructor(e,t,n){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.analyticsExtraItemsManager=n,this.useBoltClient=!1,this.useBoltEmbedded=!1}initialize(e){return gl(this,void 0,void 0,function*(){const{bolt:t,methodId:n}=e,{containerId:i,onPaymentSelect:r,useBigCommerceCheckout:o}=t||{};if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)return void(this.boltClient=yield this.boltScriptLoader.loadBoltClient());const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l,embeddedOneClickEnabled:u}=s||{},{testMode:h}=d;if(!c)throw new ni(ei.MissingPaymentMethod);if(this.boltClient=yield this.boltScriptLoader.loadBoltClient(c,h,l),this.useBoltClient=!u,this.useBoltEmbedded=!!u,this.useBoltEmbedded){if(!i)throw new vi('Unable to initialize payment because "options.bolt.containerId" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.bolt.onPaymentSelect" argument is not provided.');this.boltEmbedded=yield this.boltScriptLoader.loadBoltEmbedded(c,h,l),this.mountBoltEmbeddedField(i),r(yield this.hasBoltAccount())}})}deinitialize(){var e;return null===(e=this.embeddedField)||void 0===e||e.unmount(),this.boltClient=void 0,this.boltEmbedded=void 0,Promise.resolve()}finalize(){return Promise.reject(new Cd)}execute(e,t){return gl(this,void 0,void 0,function*(){this.setExtraItemsForAnalytics();const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{methodId:r,paymentData:o}=n||{};let a;if(!e.payment)throw new co(["payment"]);if(!r)throw new ni(ei.MissingPaymentMethod);if(!o||!function(e){return Boolean(Z(e)&&("shouldSaveInstrument"in e||"nonce"in e||ml(e)))}(o))throw new ni(ei.MissingPayment);yield this.paymentIntegrationService.submitOrder(i,t),a=this.useBoltClient?yield this.getBoltClientPaymentPayload(r,o,t):this.useBoltEmbedded?yield this.getBoltEmbeddedPaymentPayload(r,o):yield this.getBoltFullCheckoutPaymentPayload(r,o),yield this.paymentIntegrationService.submitPayment(a)})}getBoltClientPaymentPayload(e,t,n){return gl(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e,n);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e).clientToken,{isStoreCreditApplied:o}=i.getCheckoutOrThrow(),{shouldSaveInstrument:a}=t,s=this.getBoltClientOrThrow();if(yield this.paymentIntegrationService.applyStoreCredit(o),!r)throw new ni(ei.MissingPaymentMethod);const d=yield new Promise((e,t)=>{const n={success:(n,i)=>{n.reference?e(n):t(new Qr("Unable to proceed because transaction reference is unavailable. Please try again later.")),i()},close:()=>{t(new Wi)}};s.configure({orderToken:r},{},n).open()});return{methodId:e,paymentData:{nonce:d.reference,shouldSaveInstrument:a}}})}getBoltEmbeddedPaymentPayload(e,t){var n;return gl(this,void 0,void 0,function*(){if(!ml(t))throw new ni(ei.MissingPayment);const i=this.validateTokenizeResultOrThrow(yield null===(n=this.embeddedField)||void 0===n?void 0:n.tokenize());return{methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:i.token,last_four_digits:i.last4,iin:i.bin,expiration_month:+i.expiration.split("-")[1],expiration_year:+i.expiration.split("-")[0]},provider_data:{create_account:!!t.shouldCreateAccount,embedded_checkout:!0}}}}})}getBoltFullCheckoutPaymentPayload(e,t){return gl(this,void 0,void 0,function*(){yield this.setBoltOrderId();const n=this.getBoltClientOrThrow(),i=yield n.getTransactionReference();if(!i)throw new Xr;return{methodId:e,paymentData:Object.assign(Object.assign({},t),{nonce:i})}})}getBoltClientOrThrow(){if(!this.boltClient)throw new ri(ti.PaymentNotInitialized);return this.boltClient}getBoltEmbeddedOrThrow(){if(!this.boltEmbedded)throw new ri(ti.PaymentNotInitialized);return this.boltEmbedded}hasBoltAccount(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress(),i=(null==t?void 0:t.email)||(null==n?void 0:n.email)||"",r=this.getBoltClientOrThrow();try{return yield r.hasBoltAccount(i)}catch(e){throw new Xr}})}setBoltOrderId(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getOrderOrThrow(),t=this.getBoltClientOrThrow();try{yield t.setOrderId(e.orderId)}catch(e){throw new Xr}})}mountBoltEmbeddedField(e){const t=this.getBoltEmbeddedOrThrow().create("payment_field",{styles:{backgroundColor:"#fff"},renderSeparateFields:!0});t.mount(`#${e}`),this.embeddedField=t}validateTokenizeResultOrThrow(e){if(!e)throw new Xr;if(e instanceof Error)throw new yl(e.message);const{token:t,last4:n,bin:i,expiration:r}=e,o=+n,a=+i,s=+`${r}`.split("-")[1],d=+`${r}`.split("-")[0];if(!t||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(s)||Number.isNaN(d))throw new co;return e}setExtraItemsForAnalytics(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfigOrThrow(),n=e.getCartOrThrow();if(t.checkoutSettings.isAnalyticsEnabled&&pl(window)){const{id:e,lineItems:t}=n;this.analyticsExtraItemsManager.saveExtraItemsData(e,t)}}}const vl=fi(e=>new fl(e,new ao(a()),new hl(Te)),[{id:"bolt"}]);function _l(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var Sl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Il{constructor(e,t){this.paymentIntegrationService=e,this.braintreeSdk=t}initialize(e){return Sl(this,void 0,void 0,function*(){const{methodId:t,braintreeach:n}=e||{};if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');this.getMandateText=null==n?void 0:n.getMandateText,yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{clientToken:r,initializationData:o}=i;if(!r||!o)throw new ni(ei.MissingPaymentMethod);this.braintreeSdk.initialize(r);try{this.usBankAccount=yield this.braintreeSdk.getUsBankAccount()}catch(e){this.handleBraintreeError(e)}})}execute(e,t){return Sl(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const r=Nd(n.paymentData||{}),o=r?yield this.tokenizePaymentForVaultedInstrument(n):yield this.tokenizePayment(n),a=r?yield this.preparePaymentDataForVaultedInstrument(o,n):yield this.preparePaymentData(o,n);yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Sl(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}tokenizePayment({paymentData:e}){return Sl(this,void 0,void 0,function*(){const t=this.getUsBankAccountOrThrow();if(!_l(e))throw new co(["payment.paymentData"]);const n=Nd(e)?"The data are used for stored instrument verification":"function"==typeof this.getMandateText&&this.getMandateText();if(!n)throw new vi("Unable to proceed because getMandateText is not provided or returned undefined value.");try{const{nonce:i}=yield t.tokenize({bankDetails:this.getBankDetails(e),mandateText:n});return i}catch(e){this.handleBraintreeError(e)}})}tokenizePaymentForVaultedInstrument(e){return Sl(this,void 0,void 0,function*(){const{methodId:t,paymentData:n={}}=e,i=this.paymentIntegrationService.getState(),{config:r}=i.getPaymentMethodOrThrow(t);if(!r.isVaultingEnabled)throw new vi("Vaulting is disabled but a vaulted instrument was being used for this transaction");return _l(n)?this.tokenizePayment(e):null})}preparePaymentData(e,t){return Sl(this,void 0,void 0,function*(){const{methodId:n,paymentData:i={}}=t;if(!_l(i))throw new co(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,routingNumber:s,accountNumber:d}=i;return{methodId:n,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 Sl(this,void 0,void 0,function*(){const{methodId:n,paymentData:i={}}=t;if(!Nd(i)||!Bd(i))throw new co(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{instrumentId:o,shouldSetAsDefaultInstrument:a}=i;return{methodId:n,paymentData:Object.assign({deviceSessionId:r,instrumentId:o,shouldSetAsDefaultInstrument:a},e&&{nonce:e})}})}getBankDetails(e){const t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n=e.ownershipType.toLowerCase(),i=e.accountType.toLowerCase();return Object.assign(Object.assign({accountNumber:e.accountNumber,routingNumber:e.routingNumber,ownershipType:n},"personal"===n?{firstName:e.firstName,lastName:e.lastName}:{businessName:e.businessName}),{accountType:i,billingAddress:{streetAddress:t.address1,extendedAddress:t.address2,locality:t.city,region:t.stateOrProvinceCode,postalCode:t.postalCode}})}getUsBankAccountOrThrow(){if(!this.usBankAccount)throw new ri(ti.PaymentNotInitialized);return this.usBankAccount}handleBraintreeError(e){if(!Ri(e))throw e;throw new Qr(e.message)}}const wl=fi(e=>new Il(e,(e=>{const t=new Ei(e),n=new Hi(a(),window,t);return new Ui(n)})(e)),[{id:"braintreeach"}]);class Cl{constructor(e){this.paymentIntegrationService=e,this.braintreeHostWindow=window}render(e,t,n){const i=t&&document.getElementById(t);if(this.braintreeHostWindow.paypal&&i){const r=this.paymentIntegrationService.getState(),o=r.getCartOrThrow(),a=r.getBillingAddressOrThrow(),s=r.getPaymentMethodOrThrow(e);if(!s.initializationData)return;const{paypalBNPLConfiguration:d=[]}=s.initializationData,c=n===vo.PAYMENT?"checkout":n,l=d&&d.find(({id:e})=>e===c);if(!l||!l.status)return;n===vo.CART&&(i.removeAttribute("data-pp-style-logo-type"),i.removeAttribute("data-pp-style-logo-position"),i.removeAttribute("data-pp-style-text-color"),i.removeAttribute("data-pp-style-text-size")),this.braintreeHostWindow.paypal.Messages({amount:o.cartAmount,buyerCountry:a.countryCode,placement:n,style:this.getPaypalMessagesStylesFromBNPLConfig(l)}).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 bl{constructor(e){const{element:t,closeElement:n,mainElement:i}=this._createElements(e);this._element=t,this._closeElement=n,this._mainElement=i}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:n="rgba(0, 0, 0, 0.8)",id:i="checkoutOverlay",transitionDuration:r=400,hasCloseButton:o=!1,innerHtml:a=null}=e||{};let s,d,c,l,u=t;if(i&&(t.id=i),a){const e=document.createElement("div");l=`${i}--overlayText`,e.className=l,e.appendChild(a),t.appendChild(e)}return o&&(c=`${i}--close`,s=document.createElement("div"),s.className=c,d=`${i}--layout`,u=document.createElement("div"),u.className=d,u.appendChild(t),u.appendChild(s)),u.appendChild(function(e){const{id:t,background:n,transitionDuration:i,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 ${i}ms ease-out;\n background: ${n};\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:i,background:n,transitionDuration:r,classLayout:d,classOverlayText:l,classClose:c})),{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:n}=e;this._addEventListener(this._element,t),this._addEventListener(this._closeElement,n),this._unregisterClick=()=>{this._removeEventListener(this._element,t),this._removeEventListener(this._closeElement,n),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 Pl={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};function Ol(e){return"object"==typeof e&&null!==e&&"name"in e&&"BraintreeError"===e.name}function El(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 Al=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Tl{constructor(e,t,n,i){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeMessages=n,this.loadingIndicator=i,this.braintreeHostWindow=window}initialize(e){return Al(this,void 0,void 0,function*(){const{braintree:t,methodId:n}=e;if(this.braintree=t,this.paymentMethod&&this.paymentMethod.nonce||(this.paymentMethod=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n)),this.paymentMethod.clientToken&&(null==t?void 0:t.bannerContainerId))return yield this.loadPaypal(),this.loadPaypalCheckoutInstance();if(this.paymentMethod.clientToken)return this.loadPaypal();const i=yield this.paymentIntegrationService.loadPaymentMethod(n);if(this.paymentMethod=i.getPaymentMethodOrThrow(n),null==t?void 0:t.bannerContainerId)return this.loadPaypalCheckoutInstance();if(!this.paymentMethod.clientToken)throw new ni(ei.MissingPaymentMethod);return this.loadPaypal()})}execute(e,t){var n;return Al(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{onError:o}=this.braintree||{};if(!i)throw new co(["payment"]);try{const e=yield this.preparePaymentData(i,r.useStoreCredit);yield this.paymentIntegrationService.submitOrder(r,t),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.isProviderError(e)&&(yield this.loadPaypal(),null===(n=this.paypalButtonRender)||void 0===n||n.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 Cd)}deinitialize(){var e;return this.braintreeTokenizePayload=void 0,null===(e=this.paypalButtonRender)||void 0===e||e.close(),this.braintreeIntegrationService.teardown()}preparePaymentData(e,t){var n;return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getOutstandingBalance(t),o=i.getStoreConfig();if(!r)throw new ni(ei.MissingCheckout);if(!o)throw new ni(ei.MissingCheckoutConfig);if(!this.paymentMethod)throw new ri(ti.PaymentNotInitialized);const{currency:a,storeProfile:{storeLanguage:s}}=o,{nonce:d,config:{isVaultingEnabled:c}}=this.paymentMethod,{methodId:l,paymentData:u={}}=e,h=(null===(n=this.braintreeTokenizePayload)||void 0===n?void 0:n.nonce)||d;if(h){const t=yield this.paymentIntegrationService.loadPaymentMethod(l);return this.paymentMethod=t.getPaymentMethod(l),Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(h)})}if(Nd(u)||(p=u,Boolean(p.instrumentId)&&!Object.prototype.hasOwnProperty.call(p,"ccNumber")&&!Object.prototype.hasOwnProperty.call(p,"ccCvv"))){if(!c)throw new vi("Vaulting is disabled but a vaulted instrument was being used for this transaction");return Promise.resolve(e)}var p;if(!Bd(u))throw new ni(ei.MissingPayment);const{shouldSaveInstrument:m,shouldSetAsDefaultInstrument:y}=u;if(m&&!c)throw new vi("Vaulting is disabled but shouldSaveInstrument is set to true");const g=i.getShippingAddress(),f=g?El(g):void 0;return Promise.all([this.braintreeIntegrationService.paypal({amount:r,locale:s,currency:a.code,offerCredit:"braintreepaypalcredit"===this.paymentMethod.id,shippingAddressOverride:f,shouldSaveInstrument:m||!1,shippingAddressEditable:!1}),this.braintreeIntegrationService.getSessionId()]).then(([{nonce:t,details:n}={},i])=>Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(t,n&&n.email,i,m,y)}))})}formattedPayload(e,t,n,i,r){return{formattedPayload:{vault_payment_instrument:i||null,set_as_default_stored_instrument:r||null,device_info:n||null,paypal_account:{token:e,email:t||null}}}}loadPaypalCheckoutInstance(){return Al(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t,id:n}=this.paymentMethod||{};if(!e)throw new ni(ei.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e);const i={currency:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,intent:null==t?void 0:t.intent,isCreditEnabled:null==t?void 0:t.isCreditEnabled},r="braintreepaypalcredit"===n||!(null==t?void 0:t.isCreditEnabled);yield this.braintreeIntegrationService.getPaypalCheckout(i,e=>{var t;r&&n&&(null===(t=this.braintree)||void 0===t?void 0:t.bannerContainerId)&&this.renderPayPalMessages(n,this.braintree.bannerContainerId),this.renderPayPalButton(e)},this.handleError)}catch(e){this.handleError(e)}})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,vo.PAYMENT)}renderPayPalButton(e){const{onPaymentError:t,submitForm:n,onRenderButton:i,containerId:r,onError:o}=this.braintree||{};if(!r)return;const a=this.getSmartButtonContainerId(r);if(!document.getElementById(a))throw new vi(`Unable to initialize payment because element with id ${r} does not exist.`);if(!this.paymentMethod)throw new ri(ti.PaymentNotInitialized);this.loadingIndicatorContainer=r.split("#")[1];const{id:s,config:{testMode:d}}=this.paymentMethod,{paypal:c}=this.braintreeHostWindow,l=null==c?void 0:c.FUNDING.PAYPAL;c&&l?(this.paypalButtonRender=c.Buttons({env:d?"sandbox":"production",commit:!1,fundingSource:l,onClick:()=>{this.toggleLoadingIndicator(!0)},createOrder:()=>this.setupPayment(e,s,t),onApprove:t=>Al(this,void 0,void 0,function*(){this.braintreeTokenizePayload=yield this.tokenizePaymentOrThrow(t,e),n&&"function"==typeof n&&n()}),onCancel:()=>{this.toggleLoadingIndicator(!1)},onError:e=>{this.toggleLoadingIndicator(!1),null==o||o(e)}}),i&&"function"==typeof i&&i(),this.paypalButtonRender.isEligible()&&this.paypalButtonRender.render(`${r}`)):this.removeElement(r.split("#")[1])}setupPayment(e,t,n){return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState();try{const n=i.getCustomer(),r=i.getPaymentMethodOrThrow(t),o=i.getCheckoutOrThrow().outstandingBalance,a=i.getStoreConfigOrThrow().currency.code,s=i.getShippingAddress()||(null==n?void 0:n.addresses[0]),d=s?El(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 n&&(Ol(e)||e instanceof Xn)&&n(e),e}})}tokenizePaymentOrThrow(e,t,n){return Al(this,void 0,void 0,function*(){try{return yield t.tokenizePayment(e)}catch(e){throw n&&(Ol(e)||e instanceof Xn)&&n(e),e}})}loadPaypal(){return Al(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t}=this.paymentMethod||{};if(!e||!t)throw new ni(ei.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e),yield this.braintreeIntegrationService.getPaypal()}catch(e){this.handleError(e)}return Promise.resolve()})}handleError(e){if(!Ol(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Wi(e.message);throw new Qr(e.message)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"2046"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.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()}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const kl=fi(e=>{const t=window,n=new bl,i=new Ei(e),r=new So(new Hi(a(),t,i),t,n),o=new Cl(e);return new Tl(e,r,o,new fd({containerStyles:Pl}))},[{id:"braintreepaypal"},{id:"braintreepaypalcredit"}]);class Dl{constructor(e){this.requestSender=e}getOrderStatus(e="braintreelocalmethods",t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}var Ml=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class zl{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.braintreeSdk=t,this.braintreeRequestSender=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.isLPMsUpdateExperimentEnabled=!1,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return Ml(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,braintreelocalmethods:i}=e;if(this.gatewayId=t,!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');this.braintreelocalmethods=i,this.loadingIndicatorContainer=i.container.split("#")[1],yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(t),{clientToken:a,config:s,initializationData:d}=o,c=r.getStoreConfigOrThrow().checkoutSettings.features;if(this.isPollingEnabled=Ci(c,"PAYPAL-5258.braintree_local_methods_polling"),this.isLPMsUpdateExperimentEnabled=Ci(c,"PAYPAL-4853.add_new_payment_flow_for_braintree_lpms"),!a||!d||!s.merchantId)throw new ni(ei.MissingPaymentMethod);try{this.braintreeSdk.initialize(a),this.isNonInstantPaymentMethod(n)||(this.braintreeLocalPayment=yield this.braintreeSdk.getBraintreeLocalPayment(s.merchantId))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Ml(this,void 0,void 0,function*(){return this.toggleLoadingIndicator(!1),Promise.resolve()})}execute(e,t){return Ml(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{methodId:r}=n;this.toggleLoadingIndicator(!0),this.isNonInstantPaymentMethod(r)?yield this.executeWithNotInstantLPM(r):yield this.executeWithInstantLPM(r,i,t)})}executeWithNotInstantLPM(e){return Ml(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,n)=>{window.location.replace(t),this.toggleLoadingIndicator(!1),n()})}return this.handleError(e),Promise.reject(e)}})}executeWithInstantLPM(e,t,n){return Ml(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment)throw new Xr;yield new Promise((i,r)=>{var o;null===(o=this.braintreeLocalPayment)||void 0===o||o.startPayment(this.getInstantLPMConfig(e,t,n),this.getInstantLPMCallback(i,r,e,t,n))})})}getLPMsBasicPaymentData(){return Ml(this,void 0,void 0,function*(){const{deviceData:e}=yield this.braintreeSdk.getDataCollectorOrThrow();return{deviceSessionId:e}})}getInstantLPMConfig(e,t,n){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getBillingAddressOrThrow(),{firstName:a,lastName:s,countryCode:d}=o,{currency:c,email:l,lineItems:u}=r,h=u.physicalItems.length>0,p=i.getCheckoutOrThrow().outstandingBalance,m=i.getStoreConfigOrThrow().links.checkoutLink;return{paymentType:e,amount:p,fallback:{url:m,buttonText:"Complete Payment"},currencyCode:c.code,shippingAddressRequired:h,email:l,givenName:a,surname:s,address:{countryCode:d},onPaymentStart:(i,r)=>Ml(this,void 0,void 0,function*(){if(!this.isLPMsUpdateExperimentEnabled)return this.orderId=i.paymentId,void r();const o=yield this.getLPMsBasicPaymentData(),a=Object.assign(Object.assign({},o),{formattedPayload:{method:e,[`${e}_account`]:{order_id:i.paymentId}}});try{yield this.paymentIntegrationService.submitOrder(t,n),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,n)=>{this.initializePollingMechanism(e,t,n,this.gatewayId)}):void 0;throw t}})}}getInstantLPMCallback(e,t,n,i,r){const o=this.paymentIntegrationService.getState().getCartOrThrow();return(a,s)=>Ml(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 Xr));const d=yield this.getLPMsBasicPaymentData(),c=Object.assign(Object.assign({},d),{formattedPayload:{method:n,[`${n}_account`]:Object.assign({email:o.email,token:s.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId})}});try{return this.isLPMsUpdateExperimentEnabled||(yield this.paymentIntegrationService.submitOrder(i,r)),yield this.paymentIntegrationService.submitPayment({methodId:n,paymentData:c}),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 Di}isBraintreeRedirectError(e){var t;if("object"!=typeof e||null===e)return!1;const{body:n}=e;return!!n&&!!(null===(t=n.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:n}=e;return!!n&&(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.hasOwnProperty("order_id_saved_successfully"))}initializePollingMechanism(e,t,n,i){return Ml(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.braintreeRequestSender.getOrderStatus(i,{params:{useMetadata:!1}}),o=r.status===ki.Pending,a=r.status===ki.Completed,s=r.status===ki.Failed;if(a)return this.deinitializePollingMechanism(),t();if(s)return n();if(!a&&o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,n,i);yield this.reinitializeStrategy({methodId:e,gatewayId:i,braintreelocalmethods:this.braintreelocalmethods}),this.handleError(new wc)}catch(e){n()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}reinitializeStrategy(e){return Ml(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}}const xl=fi(e=>{const t=window,i=new Ei(e),r=new Ui(new Hi(a(),t,i)),o=n(),s=new Dl(o);return new zl(e,r,s,new fd({styles:{backgroundColor:"black"}}))},[{gateway:"braintreelocalmethods"}]);function Nl(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var Rl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.braintreeSdk=n}initialize(e){var t;return Rl(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.braintreefastlane" argument is not provided.');if(!i.onInit||"function"!=typeof i.onInit)throw new vi('Unable to initialize payment because "options.braintreefastlane.onInit" argument is not provided or it is not a function.');if(!i.onChange||"function"!=typeof i.onChange)throw new vi('Unable to initialize payment because "options.braintreefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{initializationData:a,clientToken:s}=o||{},{isFastlaneStylingEnabled:d}=a||{},c=Ci(r.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");this.is3DSEnabled=o.config.is3dsEnabled,s&&c&&this.braintreeSdk.initialize(s);const l=Ao(d?null===(t=o.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,i.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(n,l),this.shouldRunAuthenticationFlow()&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow()),yield this.initializeCardComponent(),this.onError=i.onError,i.onInit(e=>this.renderBraintreeCardComponent(e)),i.onChange(()=>this.handleBraintreeStoredInstrumentChange(n))})}execute(e,t){return Rl(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);yield this.paymentIntegrationService.submitOrder(i,t);const r=yield this.preparePaymentPayload(n.methodId);yield this.paymentIntegrationService.submitPayment(r),this.braintreeFastlaneUtils.removeSessionIdFromCookies()})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Rl(this,void 0,void 0,function*(){return this.braintreeCardComponent=void 0,Promise.resolve()})}initializeCardComponent(){return Rl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),{phone:t,firstName:n,lastName:i}=e.getBillingAddressOrThrow(),r=`${n} ${i}`,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 vi('Unable to initialize payment because "container" argument is not provided.');t.render(e)}preparePaymentPayload(e){var t,n;return Rl(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getBillingAddressOrThrow(),o=`${r.firstName} ${r.lastName}`,a=this.getPayPalInstruments()[0],s=yield this.braintreeFastlaneUtils.getDeviceSessionId(),d=Ci(i.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:c}=this.getBraintreeCardComponentOrThrow(),l=yield c({name:{fullName:o},billingAddress:this.mapToPayPalAddress(r)}),u=(null===(n=null===(t=l.paymentSource.card)||void 0===t?void 0:t.binDetails)||void 0===n?void 0:n.bin)||"",h=this.is3DSEnabled&&d?yield this.get3DS(l.id,u):void 0;return{methodId:e,paymentData:{deviceSessionId:s,nonce:h||l.id}}})}get3DS(e,t){return Rl(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=yield this.braintreeSdk.getBraintreeThreeDS(),r=n.getOrderOrThrow();return new Promise((n,o)=>{i.verifyCard({amount:null==r?void 0:r.orderAmount,nonce:e,bin:t,onLookupComplete:(e,t)=>{i.on("customer-canceled",()=>{"function"==typeof this.onError&&this.onError(new Wi),o(new Wi)}),t()}},(e,t)=>(e&&"THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT"===e.code&&("function"==typeof this.onError&&this.onError(new Wi),o(new Wi)),n(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(),n=e.getCustomerOrThrow(),i=e.getPaymentProviderCustomer(),r=Nl(i)?i:{},o=this.braintreeFastlaneUtils.getSessionIdFromCookies();return!(!n.isGuest||(null==r?void 0:r.authenticationState)===Mi.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}getBraintreeCardComponentOrThrow(){if(!this.braintreeCardComponent)throw new mi;return this.braintreeCardComponent}getPayPalInstruments(){const e=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow();return(Nl(e)?e:{}).instruments||[]}handleBraintreeStoredInstrumentChange(e){return Rl(this,void 0,void 0,function*(){const t=this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow(),{selectionChanged:n,selectedCard:i}=yield t.profile.showCardSelector();if(n){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),n=Nl(t)?t:{},r=this.braintreeFastlaneUtils.mapPayPalToBcInstrument(e,[i]);if(r&&r.length>0)return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},n),{instruments:[...r]})),r[0]}})}}const Ll=fi(e=>{const t=window,n=new Ei(e),i=new So(new Hi(a(),t,n),t),r=new Mo(e,i),o=new Hi(a(),t,n),s=new Ui(o);return new Fl(e,r,s)},[{id:"braintreeacceleratedcheckout"}]);var jl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Bl{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n}initialize(e){return jl(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!t)throw new vi('Unable to initialize payment because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState();this.paymentMethod=i.getPaymentMethodOrThrow(n);const r=i.getCheckoutOrThrow(),o=i.getStoreConfigOrThrow(),{clientToken:a,config:s}=this.paymentMethod||{};if(!a)throw new ni(ei.MissingPaymentMethod);const{onError:d=ce,onPaymentSelect:c=ce}=t;this.braintreeSdk.initialize(a);const l=yield this.braintreeSdk.getBraintreeVisaCheckout(),u=yield this.braintreeSdk.getVisaCheckoutSdk(null==s?void 0:s.testMode),h=l.createInitOptions({settings:{locale:o.storeProfile.storeLanguage,shipping:{collectShipping:!1}},paymentRequest:{currencyCode:o.currency.code,subtotal:String(r.subtotal)}});yield u.init(h),u.on("payment.success",e=>this.tokenizePayment(l,e).then(()=>Promise.all([this.paymentIntegrationService.loadCheckout(),this.paymentIntegrationService.loadPaymentMethod(n)])).then(()=>c()).catch(e=>d(e))),u.on("payment.error",(e,t)=>d(t))})}execute(e,t){var n,i;return jl(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!r)throw new vi('Unable to submit payment because "payload.payment" argument is not provided.');if(!(null===(i=null===(n=this.paymentMethod)||void 0===n?void 0:n.initializationData)||void 0===i?void 0:i.nonce))throw new ni(ei.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 Cd)}deinitialize(){return jl(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}tokenizePayment(e,t){return jl(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),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:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{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,i)),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 Qr(e.message);throw e}}const Ul=fi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new Bl(e,Ee(),i)},[{id:"braintreevisacheckout"}]);var ql=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}initialize(e){return ql(this,void 0,void 0,function*(){const{methodId:t}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState();this.venmoOptions=e.braintreevenmo;const i=n.getPaymentMethodOrThrow(t);yield this.initializeBraintreeVenmo(i)})}execute(e){return ql(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!t)throw new co(["payment"]);try{const e=yield this.preparePaymentData(t);yield this.paymentIntegrationService.submitOrder(n),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return ql(this,void 0,void 0,function*(){return yield this.braintreeIntegrationService.teardown(),Promise.resolve()})}handleError(e){if(!Ri(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Wi(e.message);throw new Qr(e.message)}initializeBraintreeVenmo(e){var t;return ql(this,void 0,void 0,function*(){const{clientToken:n}=e;if(!n)throw new ni(ei.MissingPaymentMethod);const i=Ci(this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features,"PAYPAL-5406.braintree_venmo_web_fallback_support");try{this.braintreeIntegrationService.initialize(n),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}:{}),i?{mobileWebFallBack:i}:{}))}catch(e){this.handleError(e)}})}preparePaymentData(e){return ql(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{nonce:n}=t.getPaymentMethodOrThrow(e.methodId);if(n)return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(n)});const i=yield this.braintreeVenmoTokenize(),r=yield this.braintreeIntegrationService.getSessionId();return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(i.nonce,i.details.email,r)})})}formattedPayload(e,t,n){return{formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:n||null,paypal_account:{token:e,email:t||null}}}}braintreeVenmoTokenize(){return new Promise((e,t)=>{var n;null===(n=this.braintreeVenmoCheckout)||void 0===n||n.tokenize((n,i)=>{if(n)return t(n);e(i)})})}}const Gl=fi(e=>{const t=window,n=a(),i=new Ei(e),r=new Hi(n,t,i),o=new So(r,t);return new Vl(e,o)},[{id:"braintreevenmo"}]);var Hl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeHostedForm=n}initialize(e){return Hl(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,braintree:i}=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 ni(ei.MissingPaymentMethod);this.threeDSecure=null==i?void 0:i.threeDSecure,this.onPaymentError=null==i?void 0:i.onPaymentError;try{this.braintreeIntegrationService.initialize(o,this.threeDSecure),this.isHostedPaymentFormEnabled(t,n)&&(null==i?void 0:i.form)&&(yield this.braintreeHostedForm.initialize(i.form,i.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 Hl(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!t)throw new co(["payment"]);this.isHostedFormInitialized&&this.braintreeHostedForm.validate(),yield this.paymentIntegrationService.submitOrder(n);const i=this.paymentIntegrationService.getState(),r=i.getBillingAddressOrThrow(),o=i.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 Cd)}deinitialize(){return Hl(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 n;if(Ol(e)){if(!(t&&this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:t})||"HOSTED_FIELDS_INVALID_FIELD_SELECTOR"!==e.code))return;if(e.code.startsWith("THREEDS_"))return null===(n=this.onPaymentError)||void 0===n||n.call(this,new Qr("THREEDS_VERIFICATION_FAILED")),Promise.reject();throw new Qr(e.message)}throw e}preparePaymentData(e,t,n){return Hl(this,void 0,void 0,function*(){const{paymentData:i}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e))return Object.assign(Object.assign({},r),i);const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=Bd(i)?i:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.braintreeIntegrationService.verifyCard(e,t,n):yield this.braintreeIntegrationService.tokenizeCard(e,t);return Object.assign(Object.assign({},r),{nonce:s,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})})}prepareHostedPaymentData(e,t,n){return Hl(this,void 0,void 0,function*(){const{paymentData:i}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e)){const{nonce:e}=yield this.braintreeHostedForm.tokenizeForStoredCardVerification();return Object.assign(Object.assign(Object.assign({},r),i),{nonce:e})}const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=Bd(i)?i:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.verifyCardWithHostedForm(t,n):yield this.braintreeHostedForm.tokenize(t);return Object.assign(Object.assign({},r),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,nonce:s})})}prepareAdditionalActionPaymentData(e,t){const{paymentData:n}=e,i={deviceSessionId:this.deviceSessionId,nonce:t},{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=Bd(n)?n:{};return this.isSubmittingWithStoredCard(e)&&(r||o)?Object.assign(Object.assign({},n),i):Object.assign({},i)}verifyCardWithHostedForm(e,t){return Hl(this,void 0,void 0,function*(){const n=yield this.braintreeHostedForm.tokenize(e);return this.braintreeIntegrationService.challenge3DSVerification(n,t)})}processAdditionalAction(e,t,n){return Hl(this,void 0,void 0,function*(){if(!pa(e)||!fe(e.body.errors,{code:"three_d_secure_required"}))return this.handleError(e);try{const{payer_auth_request:i}=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||!Nd(r))throw new co(["instrumentId"]);const a=o.getCardInstrumentOrThrow(r.instrumentId),{nonce:s}=yield this.braintreeIntegrationService.challenge3DSVerification({nonce:i||"",bin:a.iin},n),d=this.prepareAdditionalActionPaymentData(t,s);yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},t),{paymentData:d}))}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||!Nd(e.paymentData))}shouldPerform3DSVerification(e){return!(!this.is3dsEnabled||this.isSubmittingWithStoredCard(e))}shouldInitializeBraintreeFastlane(){var e;const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),n=Nl(t)?t:{};return(null===(e=this.paymentMethod)||void 0===e?void 0:e.initializationData.isAcceleratedCheckoutEnabled)&&!(null==n?void 0:n.authenticationState)}initializeBraintreeFastlaneOrThrow(e){return Hl(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{clientToken:r,config:o}=i;if(!r)throw new ni(ei.MissingPaymentMethod);this.braintreeIntegrationService.initialize(r,this.threeDSecure),yield this.braintreeIntegrationService.getBraintreeFastlane(n.id,o.testMode)})}}function $l(e){return"cardNumber"in e}function Yl(e){if(!Ri(e))return!1;const{details:t}=e;return void 0===t||"object"==typeof t&&null!==t&&void 0===t.invalidFieldKeys||(n=t,Array.isArray(n)&&n.every(e=>"string"==typeof e));var n}var Kl,Jl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e[e.CreditCard=0]="CreditCard",e[e.StoredCardVerification=1]="StoredCardVerification"}(Kl||(Kl={}));class Zl{constructor(e,t){this.braintreeScriptLoader=e,this.braintreeSDKVersionManager=t,this.isInitializedHostedForm=!1,this.handleBlur=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onBlur)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy),errors:this.mapErrors(e.fields)})},this.handleFocus=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onFocus)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleCardTypeChange=e=>{var t,n;const i=1===e.cards.length?e.cards[0].type.replace(/^master-card$/,"mastercard"):void 0;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onCardTypeChange)||void 0===n||n.call(t,{cardType:i})},this.handleInputSubmitRequest=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onEnter)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleValidityChange=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:this.isValidForm(e),errors:this.mapValidationErrors(e.fields)})}}initialize(e,t,n){var i,r,o,a,s;return Jl(this,void 0,void 0,function*(){this.clientToken=n,this.formOptions=e,this.type=$l(e.fields)?Kl.CreditCard:Kl.StoredCardVerification;const d=this.mapFieldOptions(e.fields,t);$(d)?this.isInitializedHostedForm=!1:(this.cardFields=yield this.createHostedFields({fields:d,styles:e.styles&&this.mapStyleOptions(e.styles)}),null===(i=this.cardFields)||void 0===i||i.on("blur",this.handleBlur),null===(r=this.cardFields)||void 0===r||r.on("focus",this.handleFocus),null===(o=this.cardFields)||void 0===o||o.on("cardTypeChange",this.handleCardTypeChange),null===(a=this.cardFields)||void 0===a||a.on("validityChange",this.handleValidityChange),null===(s=this.cardFields)||void 0===s||s.on("inputSubmitRequest",this.handleInputSubmitRequest),this.isInitializedHostedForm=!0)})}isInitialized(){return!!this.isInitializedHostedForm}deinitialize(){var e;return Jl(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 ri(ti.PaymentNotInitialized);const e=this.cardFields.getState();if(!this.isValidForm(e)){this.handleValidityChange(e);const t=this.mapValidationErrors(e.fields);throw new lo(t)}}tokenize(e){var t,n,i,r,o;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ti.PaymentNotInitialized);try{const r=yield this.cardFields.tokenize(ue({billingAddress:e&&this.mapBillingAddress(e)},J));return null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:!0,errors:{}}),{nonce:r.nonce,bin:null===(i=r.details)||void 0===i?void 0:i.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e);if(t)throw null===(o=null===(r=this.formOptions)||void 0===r?void 0:r.onValidate)||void 0===o||o.call(r,{isValid:!1,errors:t}),new lo(t)}throw e}})}tokenizeForStoredCardVerification(){var e,t,n,i,r;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ti.PaymentNotInitialized);try{const i=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:i.nonce,bin:null===(n=i.details)||void 0===n?void 0:n.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e,!0);if(t)throw null===(r=null===(i=this.formOptions)||void 0===i?void 0:i.onValidate)||void 0===r||r.call(i,{isValid:!1,errors:t}),new lo(t)}throw e}})}createHostedFields(e){return Jl(this,void 0,void 0,function*(){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadHostedFields(),i=this.braintreeSDKVersionManager.getSDKVersion()===bi?Object.assign(Object.assign({},e),{preventCursorJumps:!0}):e;return n.create(Object.assign(Object.assign({},i),{client:t}))})}getClient(){return Jl(this,void 0,void 0,function*(){if(!this.clientToken)throw new ri(ti.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($l(e)){const n={};return null==t||t.forEach(e=>{(e=>Object.values(Ni).includes(e))(e)&&(n[e]=!1)}),ue({number:Object.assign({container:`#${e.cardNumber.containerId}`,placeholder:e.cardNumber.placeholder,internalLabel:e.cardNumber.accessibilityLabel},Object.keys(n).length>0?{supportedCardBrands:n}:{}),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}},J)}return ue({number:e.cardNumberVerification&&{container:`#${e.cardNumberVerification.containerId}`,placeholder:e.cardNumberVerification.placeholder},cvv:e.cardCodeVerification&&{container:`#${e.cardCodeVerification.containerId}`,placeholder:e.cardCodeVerification.placeholder}},J)}mapStyleOptions(e){const t=(e={})=>ue({color:e.color,"font-family":e.fontFamily,"font-size":e.fontSize,"font-weight":e.fontWeight},J);return{input:t(e.default),".invalid":t(e.error),":focus":t(e.focus)}}mapFieldType(e){switch(e){case"number":return this.type===Kl.StoredCardVerification?ji.CardNumberVerification:ji.CardNumber;case"expirationDate":return ji.CardExpiry;case"cvv":return this.type===Kl.StoredCardVerification?ji.CardCodeVerification:ji.CardCode;case"cardholderName":return ji.CardName;default:throw new Error("Unexpected field type")}}mapErrors(e){const t={};if(e)for(const[n,i]of Object.entries(e))if(i&&this.isValidParam(n)){const{isValid:e,isEmpty:r,isPotentiallyValid:o}=i;t[n]={isValid:e,isEmpty:r,isPotentiallyValid:o}}return t}mapValidationErrors(e){return Object.keys(e).reduce((t,n)=>{var i;return Object.assign(Object.assign({},t),{[this.mapFieldType(n)]:(null===(i=e[n])||void 0===i?void 0:i.isValid)?void 0:[this.createInvalidError(this.mapFieldType(n))]})},{})}mapTokenizeError(e,t=!1){var n,i;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===(i=null===(n=e.details)||void 0===n?void 0:n.invalidFieldKeys)||void 0===i?void 0:i.reduce((e,t)=>{const n=this.mapFieldType(t);return Object.assign(Object.assign({},e),{[n]:[this.createInvalidError(n)]})},{})}createRequiredError(e){var t;return{fieldType:e,message:null!==(t={[ji.CardCode]:"CVV is required",[ji.CardCodeVerification]:"CVV is required",[ji.CardNumber]:"Credit card number is required",[ji.CardNumberVerification]:"Credit card number is required",[ji.CardExpiry]:"Expiration date is required",[ji.CardName]:"Full name is required"}[e])&&void 0!==t?t:"Field is required",type:"required"}}createInvalidError(e){var t,n,i,r;const o={[ji.CardCode]:{message:"Invalid card code",type:"invalid_card_code"},[ji.CardCodeVerification]:{message:"Invalid card code",type:"invalid_card_code"},[ji.CardNumber]:{message:"Invalid card number",type:"invalid_card_number"},[ji.CardNumberVerification]:{message:"Invalid card number",type:"invalid_card_number"},[ji.CardExpiry]:{message:"Invalid card expiry",type:"invalid_card_expiry"},[ji.CardName]:{message:"Invalid card name",type:"invalid_card_name"}};return{fieldType:e,message:null!==(n=null===(t=o[e])||void 0===t?void 0:t.message)&&void 0!==n?n:"Invalid field",type:null!==(r=null===(i=o[e])||void 0===i?void 0:i.type)&&void 0!==r?r:"invalid"}}isValidForm(e){return Object.keys(e.fields).every(t=>{var n;return null===(n=e.fields[t])||void 0===n?void 0:n.isValid})}isValidParam(e){return["number","cvv","expirationDate","postalCode","cardholderName","cardType"].includes(e)}}const Ql=fi(e=>{const t=window,n=new Ei(e),i=new Hi(a(),t,n),r=new So(i,t),o=new Zl(i,n);return new Wl(e,r,o)},[{id:"braintree"}]);var Xl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},eu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n};class tu{constructor(e){this._paymentIntegrationService=e}execute(e,t){var n,i;return this._isHostedPaymentFormEnabled(null===(n=e.payment)||void 0===n?void 0:n.methodId,null===(i=e.payment)||void 0===i?void 0:i.gatewayId)&&this._shouldRenderHostedForm?this._executeWithHostedForm(e,t):this._executeWithoutHostedForm(e,t)}initialize(e){if(!this._isHostedPaymentFormEnabled(null==e?void 0:e.methodId,null==e?void 0:e.gatewayId)||!this._isHostedFieldAvailable(e))return this._shouldRenderHostedForm=!1,Promise.resolve();const t=e&&e.creditCard&&e.creditCard.form,n=this._paymentIntegrationService.getState(),{paymentSettings:{bigpayBaseUrl:i=""}={}}=n.getStoreConfigOrThrow();if(!t)throw new vi;const r=this._paymentIntegrationService.createHostedForm(i,t);return r.attach().then(()=>(this._shouldRenderHostedForm=!0,this._hostedForm=r,Promise.resolve()))}deinitialize(){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve()}finalize(){return Promise.reject(new Cd)}_executeWithoutHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t),yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))})}_executeWithHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=this._hostedForm;if(!r)throw new ri(ti.PaymentNotInitialized);if(!n||!n.methodId)throw new co(["payment.methodId"]);yield this._paymentIntegrationService.submitOrder(i,t),yield r.validate().then(()=>r.submit(n))})}_isHostedPaymentFormEnabled(e,t){return!!e&&!0===this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}var nu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class iu extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.cbaMGPSScriptLoader=t,this.sessionId=""}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return nu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{methodId:n}=e;yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(n);if(!function(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&"object"==typeof e.initializationData&&null!==e.initializationData&&"merchantId"in e.initializationData&&"string"==typeof e.initializationData.merchantId&&("boolean"==typeof e.initializationData.isTestModeFlagEnabled||void 0===e.initializationData.isTestModeFlagEnabled)}(r))throw new ni(ei.MissingPaymentMethod);const{clientToken:o,initializationData:{isTestModeFlagEnabled:a=!1,merchantId:s},config:{is3dsEnabled:d}}=r;if(d){if(this.threeDSjs=yield this.cbaMGPSScriptLoader.load(a),!this.threeDSjs)throw new ri(ti.PaymentNotInitialized);if(!o||!s)throw new ni(ei.MissingPaymentMethod);if(this.sessionId=o,this.locale=i.getLocale(),!this.locale)throw new ni(ei.MissingCart);yield this.threeDSjs.configure({merchantId:s,sessionId:this.sessionId,callback:()=>{var e;if(null===(e=this.threeDSjs)||void 0===e?void 0:e.isConfigured())return this.paymentIntegrationService.getState();throw new Qr("Failed to configure 3DS API.")},configuration:{userLanguage:this.locale,wsVersion:62}})}return Promise.resolve()})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return nu(this,void 0,void 0,function*(){const{payment:i}=e,r=i&&i.paymentData;if(!i||!r)throw new co(["payment.paymentData"]);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i.methodId),{is3dsEnabled:a}=o.config;if(a){const t=Object.assign(Object.assign({},r),{threeDSecure:{token:this.sessionId}});e.payment&&(e.payment.paymentData=t)}return n.execute.call(this,e,t).catch(e=>{if(!a||!pa(e)||!fe(e.body.errors,{code:"three_d_secure_required"}))return Promise.reject(e);const t=this.paymentIntegrationService.getState(),n=t.getOrder(),{storeProfile:{storeId:i}}=t.getStoreConfigOrThrow();if(!n||!this.sessionId)throw new ni(ei.MissingCheckout);const r=`${i}_${n.orderId}`;if("object"!=typeof(o=e.body)||null===o||!("three_ds_result"in o)||"object"!=typeof o.three_ds_result||null===o.three_ds_result||!("token"in o.three_ds_result)||"string"!=typeof o.three_ds_result.token)throw new nr;var o;const{three_ds_result:{token:s}}=e.body;return s?this.initiateAuthentication(r,s):Promise.reject(e)})})}finalize(e){return nu(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}deinitialize(){return this.threeDSjs=void 0,this.sessionId="",super.deinitialize()}initiateAuthentication(e,t){return nu(this,void 0,void 0,function*(){const n=yield new Promise((n,i)=>{if(!this.threeDSjs)throw new ri(ti.PaymentNotInitialized);this.threeDSjs.initiateAuthentication(e,t,e=>{const t=e.error;return t?i(new Qr(t.msg)):this.threeDSjs&&"PROCEED"===e.gatewayRecommendation?n(e.restApiResponse):i(new Qr)})});if(n.transaction&&"AUTHENTICATION_AVAILABLE"===n.transaction.authenticationStatus)return this.authenticatePayer(e,t);throw new Qr})}authenticatePayer(e,t,n=1){return nu(this,void 0,void 0,function*(){return new Promise((i,r)=>{if(!this.threeDSjs)return r(new ri(ti.PaymentNotInitialized));this.threeDSjs.authenticatePayer(e,t,i=>nu(this,void 0,void 0,function*(){const o=i.error;return o?o.cause&&"SERVER_BUSY"===o.cause&&n<5?(yield new Promise(e=>setTimeout(e,3e3)),this.authenticatePayer(e,t,++n)):r(new Qr):new Promise(ce)}),{fullScreenRedirect:!0})})})}}class ru{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e){return t=this,n=void 0,r=function*(){if(yield this._scriptLoader.loadScript(`//${e?"test":"ap"}-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js`),!this._window.ThreeDS)throw new mi;return this._window.ThreeDS},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const ou=fi(e=>new iu(e,new ru(a())),[{id:"cba_mpgs"}]);var au;!function(e){e.OffsiteRedirect="offsite_redirect"}(au||(au={}));class su extends tu{constructor(e){super(e),this.paymentIntegrationService=e}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new Cd)}_executeWithHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=this._hostedForm;if(!r)throw new ri(ti.PaymentNotInitialized);if(!n||!n.methodId)throw new co(["payment.methodId"]);try{yield r.validate(),yield this.paymentIntegrationService.submitOrder(i,t),yield r.submit(n)}catch(e){return this._processResponse(e)}this.paymentIntegrationService.loadCurrentOrder()},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_processResponse(e){if(!pa(e))return Promise.reject(e);const t=e.body.additional_action_required;return t&&t.type===au.OffsiteRedirect?this._performRedirect(t):Promise.reject(e)}_performRedirect(e){return new Promise(()=>{window.location.replace(e.data.redirect_url)})}}class du extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(n.methodId,r)})}))}catch(e){return this._processResponse(e)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_createFormattedPayload(e,t){if("fawry"===e&&"customerMobile"in t&&"customerEmail"in t){const e=t;return{customerMobile:e.customerMobile,customerEmail:e.customerEmail}}}}const cu=fi(e=>new du(e),[{gateway:"checkoutcom",id:"fawry"}]);function lu(e){return pa(e)&&fe(e.body.errors,{code:"three_d_secure_required"})}var uu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},hu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n};class pu extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.formPoster=t}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new Cd)}_executeWithoutHostedForm(e,t){return uu(this,void 0,void 0,function*(){const{payment:n}=e,i=hu(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this.paymentIntegrationService.submitOrder(i,t);try{yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))}catch(e){return lu(e)?this._handleThreeDSecure(e):Promise.reject(e)}})}_executeWithHostedForm(e,t){return uu(this,void 0,void 0,function*(){const{payment:n}=e,i=hu(e,["payment"]),r=this._hostedForm;if(!r)throw new ri(ti.PaymentNotInitialized);if(!n||!n.methodId)throw new co(["payment.methodId"]);try{yield r.validate(),yield this.paymentIntegrationService.submitOrder(i,t),yield r.submit(n)}catch(e){return lu(e)?this._handleThreeDSecure(e):Promise.reject(e)}this.paymentIntegrationService.loadCurrentOrder()})}_handleThreeDSecure(e){const{acs_url:t,payer_auth_request:n,callback_url:i,merchant_data:r}=e.body.three_ds_result;return new Promise(()=>this.formPoster.postForm(t,{PaReq:n||null,TermUrl:i||null,MD:r||null}))}}const mu=fi(e=>new pu(e,Ee()),[{gateway:"checkoutcom",id:"credit_card"},{gateway:"checkoutcom",id:"card"}]);class yu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=null==n?void 0:n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(n.methodId,r)})}))}catch(e){return this._processResponse(e)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_createFormattedPayload(e,t){const n={iban:"",bic:""},{iban:i,bic:r}="iban"in t&&"bic"in t?t:n;return"sepa"===e&&document&&(n.iban=i,n.bic=r),n}}const gu=fi(e=>new yu(e),[{gateway:"checkoutcom",id:"sepa"}]);class fu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=null==n?void 0:n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(n.methodId,r)})}))}catch(e){return this._processResponse(e)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_createFormattedPayload(e,t){if("ideal"===e&&"bic"in t)return{bic:t.bic}}}const vu=fi(e=>new fu(e),[{gateway:"checkoutcom",id:"ideal"}]);const _u=["boleto","oxxo","qpay","ideal"];class Su extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=null==n?void 0:n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(n.methodId,r)})}))}catch(e){return this._processResponse(e)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_createFormattedPayload(e,t){const n={ccDocument:""},i="ccDocument"in t?t.ccDocument:"";return-1!==_u.indexOf(e)&&i&&(n.ccDocument=i),n}}const Iu=fi(e=>new Su(e),[{gateway:"checkoutcom"}]);var wu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cu{constructor(e,t){this._paymentIntegrationService=e,this._clearpayScriptLoader=t}initialize(e){return wu(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:t}=this._paymentIntegrationService.getState(),n=t(e.methodId,e.gatewayId),i=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features;this._clearpaySdk=yield this._clearpayScriptLoader.load(n,i)})}deinitialize(){return this._clearpaySdk=void 0,Promise.resolve()}execute(e,t){return wu(this,void 0,void 0,function*(){const{gatewayId:n,methodId:i}=e.payment||{};if(!n||!i)throw new co(["payment.gatewayId","payment.methodId"]);const r=this._paymentIntegrationService.getState(),{isStoreCreditApplied:o}=r.getCheckoutOrThrow();yield this._paymentIntegrationService.applyStoreCredit(o),yield this._paymentIntegrationService.validateCheckout(r.getCheckout(),t);const{countryCode:a}=r.getBillingAddressOrThrow();if(!this._isCountrySupported(a))throw new vi("Unable to proceed because billing country is not supported.");return yield this._loadPaymentMethod(n,i,t),yield this._redirectToClearpay(a,this._paymentIntegrationService.getState().getPaymentMethod(i,n)),new Promise(ce)})}finalize(e){var t,n,i;return wu(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ni(ei.MissingCheckout);if(!a||!a.payment.token)throw new ni(ei.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToClearpay(e,t){return wu(this,void 0,void 0,function*(){if(!this._clearpaySdk||!t||!t.clientToken)throw new ri(ti.PaymentNotInitialized);return this._clearpaySdk.initialize({countryCode:e}),this._clearpaySdk.redirect({token:t.clientToken}),Promise.resolve()})}_isCountrySupported(e){return"GB"===e}_loadPaymentMethod(e,t,n){var i;return wu(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new vi("Clearpay can't process your payment for this order, please try another payment method");throw e}})}}class bu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t={}){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript(this._getScriptUrl(e.config.testMode,t)),!this._window.AfterPay)throw new mi;return this._window.AfterPay},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getScriptUrl(e,t={}){const n=Ci(t,"PI-4555.clearpay_add_https_to_prod_script",!1);return e?n?"https://portal.sandbox.clearpay.co.uk/afterpay-async.js":"//portal.sandbox.clearpay.co.uk/afterpay-async.js":n?"https://portal.clearpay.co.uk/afterpay-async.js":"//portal.clearpay.co.uk/afterpay-async.js"}}const Pu=fi(e=>new Cu(e,new bu(a())),[{gateway:"clearpay"},{id:"clearpay"}]),Ou=fi(e=>new tu(e),[{default:!0}]);var Eu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Au{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return Eu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode),yield this._cardinalClient.configure(yield this._getClientToken(e))})}start(e,t,n,i){return Eu(this,void 0,void 0,function*(){const{getCardInstrument:r,getPaymentMethodOrThrow:o}=this._paymentIntegrationService.getState(),{payment:{methodId:a="",paymentData:s={}}={}}=t,d=Nd(s)&&r(s.instrumentId),c=d?d.iin:i&&i.getBin();c&&(yield this._cardinalClient.runBinProcess(c));try{return yield e(de(t,{payment:{paymentData:{threeDSecure:{token:o(a).clientToken}}}}),n)}catch(e){if(!pa(e)||!fe(e.body.errors,{code:"three_d_secure_required"}))throw e;const n=yield this._cardinalClient.getThreeDSecureData(e.body.three_ds_result,this._getOrderData());if(!i)return void(yield this._paymentIntegrationService.submitPayment(de(t.payment,{paymentData:{threeDSecure:n}})));yield i.submit(de(t.payment,{paymentData:{threeDSecure:n}}))}})}_getClientToken(e){return Eu(this,void 0,void 0,function*(){return e.clientToken?e.clientToken:(yield this._paymentIntegrationService.loadPaymentMethod(e.id),this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.id).clientToken||"")})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),i=e.getCheckoutOrThrow(),r=e.getOrderOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i.cart.currency.code,id:r.orderId.toString(),amount:i.cart.cartAmount}}}const Tu=[100004,1010,1011,1020];var ku,Du,Mu,zu,xu,Nu,Ru;!function(e){e.SetupCompleted="payments.setupComplete",e.Validated="payments.validated"}(ku||(ku={})),function(e){e.Init="init",e.Complete="complete",e.Confirm="confirm"}(Du||(Du={})),function(e){e.Success="SUCCESS",e.NoAction="NOACTION",e.Failure="FAILURE",e.Error="ERROR"}(Mu||(Mu={})),function(e){e.CCA="CCA",e.Paypal="Paypal",e.Wallet="Wallet",e.VisaCheckout="VisaCheckout",e.ApplePay="ApplePay",e.DiscoverWallet="DiscoverWallet"}(zu||(zu={})),function(e){e.BinProcess="bin.process"}(xu||(xu={})),function(e){e.CCA="cca"}(Nu||(Nu={})),function(e){e.Yes="Y",e.No="N"}(Ru||(Ru={}));class Fu{constructor(e){this._scriptLoader=e,this._provider="",this._testMode=!1,this._configurationToken=""}load(e,t=!1){return this._provider=e,this._testMode=t,this._sdk||(this._sdk=this._scriptLoader.load(e,t)),this._sdk.then(ce)}configure(e){if(this._configurationToken){if(this._configurationToken===e)return Promise.resolve();this._sdk=this._scriptLoader.load(`${this._provider}.${Date.now()}`,this._testMode)}return this._getClientSDK().then(t=>new Promise((n,i)=>{t.on(ku.SetupCompleted,()=>{t.off(ku.SetupCompleted),t.off(ku.Validated),this._configurationToken=e,n()}),t.on(ku.Validated,e=>{t.off(ku.SetupCompleted),t.off(ku.Validated),e.ActionCode===Mu.Error&&(H(Tu,e.ErrorNumber)&&i(new ni(ei.MissingPaymentMethod)),i(new Qr(e.ErrorDescription)))}),t.setup(Du.Init,{jwt:e})}))}runBinProcess(e){return this._getClientSDK().then(t=>t.trigger(xu.BinProcess,e).catch(ce)).then(e=>{if(!e||!e.Status)throw new ri(ti.PaymentNotInitialized)})}getThreeDSecureData(e,t){return this._getClientSDK().then(n=>new Promise((i,r)=>{n.on(ku.Validated,(e,t)=>{if(n.off(ku.Validated),!t)return r(new Qr(e.ErrorDescription?e.ErrorDescription:"An error was encountered while processing the transaction."));if(!e.ActionCode)return i({token:t});switch(e.ActionCode){case Mu.Success:return i({token:t});case Mu.NoAction:return e.ErrorNumber>0?r(new Qr(e.ErrorDescription)):e.Payment&&e.Payment.ExtendedData&&e.Payment.ExtendedData.SignatureVerification===Ru.Yes?i({token:t}):r(new Qr("Transaction signature could not be validated."));case Mu.Failure:return r(new Qr("User failed authentication or an error was encountered while processing the transaction."));case Mu.Error:return r(new Qr(e.ErrorDescription))}});const o={AcsUrl:e.acs_url,Payload:e.merchant_data},a=this._mapToPartialOrder(t,e.payer_auth_request);n.continue(Nu.CCA,o,a)}))}_mapToPartialOrder(e,t){const n={BillingAddress:this._mapToCardinalAddress(e.billingAddress)};return e.paymentData&&(n.Account=this._mapToCardinalAccount(e.paymentData)),e.billingAddress.email&&(n.Email1=e.billingAddress.email),e.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(e.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:e.id,Amount:e.amount,CurrencyCode:e.currencyCode,OrderChannel:"S",TransactionId:t}}}_mapToCardinalAccount(e){return{AccountNumber:Number(e.ccNumber),ExpirationMonth:Number(e.ccExpiry.month),ExpirationYear:Number(e.ccExpiry.year),NameOnAccount:e.ccName,CardCode:Number(e.ccCvv)}}_mapToCardinalAddress(e){const t={FirstName:e.firstName,LastName:e.lastName,Address1:e.address1,City:e.city,State:e.stateOrProvince,PostalCode:e.postalCode,CountryCode:e.countryCode};return e.address2&&(t.Address2=e.address2),e.phone&&(t.Phone1=e.phone),t}_getClientSDK(){if(!this._sdk)throw new ri(ti.PaymentNotInitialized);return this._sdk}}class Lu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t){const n=t?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js";return this._scriptLoader.loadScript(`${n}?v=${e}`).then(()=>{if(!this._window.Cardinal)throw new mi;return this._window.Cardinal})}}var ju=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Bu extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return ju(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return ju(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Uu=fi(e=>new Bu(e,new Au(e,new Fu(new Lu(a())))),[{id:"cybersource"}]);var qu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vu{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return qu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode)})}start(e,t,n,i){var r,o,a,s;return qu(this,void 0,void 0,function*(){const{getCardInstrument:d}=this._paymentIntegrationService.getState(),{payment:c={methodId:""}}=t,{paymentData:l={}}=c;try{return yield e(t,n)}catch(e){if(pa(e)&&"additional_action_required"===(null===(r=e.body)||void 0===r?void 0:r.status)){const t=null===(a=null===(o=e.body.additional_action_required)||void 0===o?void 0:o.data)||void 0===a?void 0:a.token,n=null===(s=e.body.three_ds_result)||void 0===s?void 0:s.payer_auth_request;yield this._cardinalClient.configure(t);const r=this._getBin(l,d,i);r&&(yield this._cardinalClient.runBinProcess(r));try{return yield this._submitPayment(c,{xid:n},i)}catch(e){if(pa(e)&&fe(e.body.errors,{code:"three_d_secure_required"})){const t=e.body.three_ds_result,n=null==t?void 0:t.payer_auth_request;return yield this._cardinalClient.getThreeDSecureData(t,this._getOrderData()),this._submitPayment(c,{token:n},i)}throw e}}throw e}})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),{cart:{currency:{code:i},cartAmount:r}}=e.getCheckoutOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i,id:e.getOrderOrThrow().orderId.toString(),amount:r}}_submitPayment(e,t,n){return qu(this,void 0,void 0,function*(){const i=de({},e,{paymentData:{threeDSecure:t}});n||(yield this._paymentIntegrationService.submitPayment(i)),yield null==n?void 0:n.submit(i)})}_getBin(e,t,n){const i=Nd(e)&&t(e.instrumentId),r=function(e){const t=e;return!Nd(t)&&"string"==typeof t.ccName&&"string"==typeof t.ccNumber&&"object"==typeof t.ccExpiry&&"string"==typeof t.ccExpiry.month&&"string"==typeof t.ccExpiry.year}(e)&&e.ccNumber,o=n?n.getBin():r;return(i?i.iin:o)||""}}var Gu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hu extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Gu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Gu(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Wu=fi(e=>new Hu(e,new Vu(e,new Fu(new Lu(a())))),[{id:"cybersourcev2"},{id:"bnz"}]);function $u(e){return"object"==typeof e&&null!==e&&"errors"in e&&Array.isArray(e.errors)&&"code"in e.errors[0]&&"string"==typeof e.errors[0].code&&"provider_data"in e&&"object"==typeof e.provider_data}var Yu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ku extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ni(ei.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}processAdditionalAction(e){return Yu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ti.PaymentNotInitialized);return this._adyenClient}}var Ju=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zu{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t,this._isDeinitializationBlocked=!1,this._loadingIndicator=new fd({containerStyles:yd})}initialize(e){var t,n;return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new vi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!(null==i?void 0:i.walletButton))throw new vi("Unable to proceed without valid options.");const{walletButton:r,loadingContainerId:o}=i,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(i,["walletButton","loadingContainerId"]);this._loadingIndicatorContainer=o,yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());const s=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(this._getMethodId());this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(t=s.initializationData)||void 0===t?void 0:t.isWebViewExperimentOn)),yield this._googlePayPaymentProcessor.initialize(()=>s,this._getGooglePayClientOptions(null===(n=s.initializationData)||void 0===n?void 0:n.storeCountry)),this._addPaymentButton(r,a)})}execute({payment:e}){return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();const t=yield this._googlePayPaymentProcessor.getNonce(e.methodId),n=yield this._googlePayPaymentProcessor.extraPaymentData();try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign({nonce:t},n)}))}catch(t){yield this._googlePayPaymentProcessor.processAdditionalAction(t,e.methodId)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this._isDeinitializationBlocked||(this._clickListener&&(null===(e=this._paymentButton)||void 0===e||e.removeEventListener("click",this._clickListener)),this._paymentButton=void 0,this._clickListener=void 0,this._methodId=void 0),Promise.resolve()}_addPaymentButton(e,t){if(this._paymentButton)return;const n=document.getElementById(e);if(!n)throw new vi("Unable to proceed without a walletButton.");this._paymentButton=n,this._clickListener=this._handleClick(t),this._paymentButton.addEventListener("click",this._clickListener)}_handleClick({onPaymentSelect:e,onError:t}){return n=>Ju(this,void 0,void 0,function*(){n.preventDefault();try{this._googlePayPaymentProcessor.setShouldRequestShipping(!1),yield this._googlePayPaymentProcessor.initializeWidget(),this._isDirectPayOnClickEnabled()?yield this._interactWithPaymentSheetAndPay():yield this._interactWithPaymentSheet()}catch(e){let n=e;if(this._toggleLoadingIndicator(!1),ta(e)){if("CANCELED"===e.statusCode)throw new Wi;n=new Qr(JSON.stringify(e))}throw null==t||t(new Qr("An error occurred while requesting your Google Pay payment details.")),n}finally{this._toggleBlockDeinitialization(!1)}null==e||e()})}_interactWithPaymentSheetAndPay(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet();this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const t=this._getMethodId(),n=this._paymentIntegrationService.getState(),{features:i}=n.getStoreConfigOrThrow().checkoutSettings,r=Ci(i,"PI-5031.google_pay_dont_override_address"),o=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);o&&!r&&(yield this._paymentIntegrationService.updateBillingAddress(o)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(t,e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(t);const a=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(t);yield this._googlePayPaymentProcessor.initialize(()=>a),yield this.execute({useStoreCredit:!1,payment:{methodId:t}}),this._completeCheckoutFlow()})}_completeCheckoutFlow(){window.location.replace("/checkout/order-confirmation"),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)}_interactWithPaymentSheet(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._paymentIntegrationService.getState(),{features:n}=t.getStoreConfigOrThrow().checkoutSettings,i=Ci(n,"PI-5031.google_pay_dont_override_address");this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const r=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);r&&!i&&(yield this._paymentIntegrationService.updateBillingAddress(r)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(this._getMethodId(),e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)})}_getMethodId(){return ii(this._methodId,()=>new ri(ti.PaymentNotInitialized))}_getIsSignedInOrThrow(){return Ju(this,void 0,void 0,function*(){try{return!!(yield this._googlePayPaymentProcessor.getNonce(this._getMethodId()))}catch(e){if(e instanceof ni&&e.subtype===ei.MissingPaymentToken)return!1;throw e}})}_handleOfferTrigger(e){return Ju(this,void 0,void 0,function*(){let t=!1,n="Sign in to Google Pay first to apply or remove promo codes.";try{t=yield this._getIsSignedInOrThrow()}catch(e){e instanceof ni&&(n=e.message)}if(t){const{newOfferInfo:t,error:n}=yield this._googlePayPaymentProcessor.handleCoupons(e);return{newOfferInfo:t,error:n}}return{error:{reason:Ko.OFFER_INVALID,message:n,intent:Jo.OFFER}}})}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,offerData:n})=>Ju(this,void 0,void 0,function*(){if(t!==Jo.INITIALIZE&&t!==Jo.OFFER)return;const{offerChangeTriggers:i}=this._googlePayPaymentProcessor.getCallbackTriggers(),{newOfferInfo:r,error:o}=i.includes(t)?yield this._handleOfferTrigger(n):{},a=o;yield this._paymentIntegrationService.loadCheckout();const{code:s}=this._paymentIntegrationService.getState().getCartOrThrow().currency,d=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:s,totalPriceStatus:Wo.FINAL,totalPrice:d})},r&&{newOfferInfo:r}),a&&{error:a})})}}}_isDirectPayOnClickEnabled(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return Ci(e,"PI-5111.google_pay_direct_pay_on_click")}_toggleBlockDeinitialization(e){this._isDeinitializationBlocked=e}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this._loadingIndicator.show(this._loadingIndicatorContainer):this._loadingIndicator.hide()}}const Qu=fi(e=>new Zu(e,new aa(da(),new Ku(e,new zd(a(),s())),n(),Ee())),[{id:"googlepayadyenv2"}]);var Xu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class eh extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ni(ei.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}processAdditionalAction(e){return Xu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ti.PaymentNotInitialized);return this._adyenClient}}const th=fi(e=>new Zu(e,new aa(da(),new eh(e,new jd(a(),s())),n(),Ee())),[{id:"googlepayadyenv3"}]),nh=fi(e=>new Zu(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),ih=fi(e=>{const t=n();return new Zu(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),rh=fi(e=>new Zu(e,new aa(da(),new va(e),n(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),oh=fi(e=>new Zu(e,new aa(da(),new Ia(e),n(),Ee())),[{id:"googlepayorbital"}]),ah=fi(e=>new Zu(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),sh=fi(e=>new Zu(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]),dh=fi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new Zu(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]);var ch,lh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(ch||(ch={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(lh||(lh={}));var uh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalCommerceSdk=n,this._requestSender=i}execute({payment:e}){return uh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return uh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ni(ei.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalCommerceSdk.getPayPalGooglePaySdk(i,r,n.getLocale(),!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===ch.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==ch.Approved)throw new vi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return uh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepaypaypalcommercecheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const ph=fi(e=>{const t=new Xa(a());return new hh(e,new aa(da(),new ns(e,t),n(),Ee()),t,n())},[{id:"googlepaypaypalcommerce"}]);var mh,yh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(mh||(mh={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(yh||(yh={}));var gh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalSdkHelper=n,this._requestSender=i}execute({payment:e}){return gh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return gh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ni(ei.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalSdkHelper.getPayPalGooglePaySdk(i,r,!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===mh.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==mh.Approved)throw new vi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return gh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepay_bigcommerce_paymentscheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const vh=fi(e=>{const t=new Nr(a());return new fh(e,new aa(da(),new os(e,t),n(),Ee()),t,n())},[{id:"googlepay_bigcommerce_payments"}]),_h=fi(e=>new Zu(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);class Sh extends Xn{constructor(e,t,n){super(n||"Payment cannot be processed for this order, please select another payment method"),this.type="custom_provider_execute_error",this.name=t,this.subtype=e}}class Ih{constructor(e,t){this.paymentIntegrationService=e,this.formPoster=t}execute(e,t){var n,i,r,o,a;return i=this,r=void 0,a=function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!(null==i?void 0:i.methodId))throw new co(["payment.methodId"]);yield this.paymentIntegrationService.loadPaymentMethod(i.methodId,t);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i.methodId);if(!(null===(n=o.initializationData)||void 0===n?void 0:n.processable))throw new Sh("payment.humm_not_processable_error","hummNotProcessableError");yield this.paymentIntegrationService.submitOrder(r,t);try{yield this.paymentIntegrationService.submitPayment({methodId:i.methodId})}catch(e){return this.isOffsiteRedirectResponse(e)?this.handleOffsiteRedirectResponse(e):Promise.reject(e)}},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}handleOffsiteRedirectResponse(e){const t=e.body.additional_action_required.data.redirect_url,n=e.body.provider_data;return new Promise(e=>{this.formPoster.postForm(t,JSON.parse(n),e)})}isOffsiteRedirectResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!t.body)return!1;const n=t.body;return"additional_action_required"===n.status&&!!n.additional_action_required&&"offsite_redirect"===n.additional_action_required.type&&"string"==typeof n.provider_data}}const wh=fi(e=>new Ih(e,Ee()),[{id:"humm"}]),Ch=["AT","BE","CA","CH","CZ","DE","DK","ES","FI","FR","GB","GR","IE","IT","NL","NO","NZ","PL","PT","SE"],bh=["AU"];var Ph=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Oh{constructor(e,t){this.paymentIntegrationService=e,this.klarnaScriptLoader=t}initialize(e){return Ph(this,void 0,void 0,function*(){this.klarnaCredit=yield this.klarnaScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Ph(this,void 0,void 0,function*(){if(!e.payment)throw new vi('Unable to proceed because "payload.payment" argument is not provided.');const n=e.payment,{paymentData:i}=n,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(n,["paymentData"]),{authorization_token:o}=yield this.authorize();yield this.paymentIntegrationService.initializePayment(r.methodId,{authorizationToken:o}),yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:r,useStoreCredit:e.useStoreCredit}),t)})}finalize(){return Promise.reject(new Cd)}loadWidget(e){return Ph(this,void 0,void 0,function*(){if(!e.klarna)throw new vi('Unable to load widget because "options.klarna" argument is not provided.');const{methodId:t,klarna:{container:n,onLoad:i}}=e;return yield this.paymentIntegrationService.loadPaymentMethod(t),new Promise(e=>{const r=this.paymentIntegrationService.getState().getPaymentMethod(t);if(!r)throw new ni(ei.MissingPaymentMethod);if(!this.klarnaCredit||!r.clientToken)throw new ri(ti.PaymentNotInitialized);this.klarnaCredit.init({client_token:r.clientToken}),this.klarnaCredit.load({container:n},t=>{i&&i(t),e(t)})})})}getUpdateSessionData(e,t){if(!H([...Ch,...bh],e.countryCode))return{};const n={billing_address:this.mapToKlarnaAddress(e,e.email)};return t&&(n.shipping_address=this.mapToKlarnaAddress(t,e.email)),n}needsStateCode(e){return H(bh,e)}mapToKlarnaAddress(e,t){const n={street_address:e.address1,city:e.city,country:e.countryCode,given_name:e.firstName,family_name:e.lastName,postal_code:e.postalCode,region:this.needsStateCode(e.countryCode)?e.stateOrProvinceCode:e.stateOrProvince,email:t};return e.address2&&(n.street_address2=e.address2),e.phone&&(n.phone=e.phone),n}authorize(){return new Promise((e,t)=>{const n=this.paymentIntegrationService.getState(),i=n.getBillingAddress(),r=n.getShippingAddress();if(!i)throw new ni(ei.MissingBillingAddress);if(!this.klarnaCredit)throw new ri(ti.PaymentNotInitialized);const o=this.getUpdateSessionData(i,r);this.klarnaCredit.authorize(o,n=>n.approved?e(n):n.show_form?t(new Wi):void t(new Xr))})}}class Eh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Credit)||(yield this.scriptLoader.loadScript("//credit.klarnacdn.net/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Credit))throw new mi;return this.klarnaWindow.Klarna.Credit},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}const Ah=fi(e=>new Oh(e,new Eh(a())),[{id:"klarna"}]);var Th=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class kh{constructor(e,t,n){this.paymentIntegrationService=e,this.klarnav2ScriptLoader=t,this.klarnav2TokenUpdater=n}initialize(e){return Th(this,void 0,void 0,function*(){this.klarnaPayments=yield this.klarnav2ScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadPaymentsWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadPaymentsWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Th(this,void 0,void 0,function*(){if(!e.payment)throw new vi('Unable to proceed because "payload.payment" argument is not provided.');const n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e.payment,[]),{gatewayId:i,methodId:r}=n;if(!i)throw new vi('Unable to proceed because "payload.payment.gatewayId" argument is not provided.');const o=this.paymentIntegrationService.getState(),{id:a}=o.getCartOrThrow(),{clientToken:s,initializationData:d}=o.getPaymentMethodOrThrow(r),{klarnaMultipleRadioButton:c}=d||{};yield this.klarnav2TokenUpdater.klarnaOrderInitialization(a,s);const l=this.isKlarnaMultipleRadioButtonEnabled(c,i,r),{authorization_token:u}=yield this.authorizeOrThrow(l,r);yield this.paymentIntegrationService.initializePayment(i,{authorizationToken:u}),yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:n,useStoreCredit:e.useStoreCredit}),t)})}finalize(){return Promise.reject(new Cd)}loadPaymentsWidget(e){return Th(this,void 0,void 0,function*(){if(!e.klarnav2)throw new vi('Unable to load widget because "options.klarnav2" argument is not provided.');const{methodId:t,gatewayId:n,klarnav2:{container:i,onLoad:r}}=e;if(!n)throw new vi('Unable to proceed because "payload.payment.gatewayId" argument is not provided.');const o=this.paymentIntegrationService.getState(),a={params:o.getCartOrThrow().id};return yield this.klarnav2TokenUpdater.updateClientToken(n,{params:a}).catch(()=>{throw new ni(ei.MissingPaymentMethod)}),new Promise(e=>{const a=o.getPaymentMethodOrThrow(t),{klarnaMultipleRadioButton:s}=a.initializationData||{};if(!this.klarnaPayments||!a.clientToken)throw new ri(ti.PaymentNotInitialized);this.klarnaPayments.init({client_token:a.clientToken}),this.klarnaPayments.load({container:i,payment_method_category:this.isKlarnaMultipleRadioButtonEnabled(s,n,t)},t=>{r&&r(t),e(t)})})})}getUpdateSessionData(e,t,n){if(!H([...Ch,...bh],t.countryCode))return{};const i={billing_address:this.mapToKlarnaAddress(e,t,t.email)};return n&&(i.shipping_address=this.mapToKlarnaAddress(e,n,t.email)),i}needsStateCode(e){return H(bh,e)}isKlarnaMultipleRadioButtonEnabled(e,t,n){return e?n:t}mapToKlarnaAddress(e,t,n){const i=this.paymentIntegrationService.getState(),{checkoutSettings:r}=i.getStoreConfigOrThrow(),o=i.getPaymentMethodOrThrow(e),{enableBillie:a}=o.initializationData||{},s={street_address:t.address1,city:t.city,country:t.countryCode,given_name:t.firstName,family_name:t.lastName,postal_code:t.postalCode,region:this.needsStateCode(t.countryCode)?t.stateOrProvinceCode:t.stateOrProvince,email:n};return t.address2&&(s.street_address2=t.address2),t.phone&&(s.phone=t.phone),t.company&&a&&Ci(r.features,"PI-3915.b2b_payment_session_for_klarna")&&(s.organization_name=t.company),s}authorizeOrThrow(e,t){return Th(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const n=this.paymentIntegrationService.getState(),i=n.getBillingAddressOrThrow(),r=n.getShippingAddress(),o=this.getUpdateSessionData(t,i,r);return new Promise((t,n)=>{if(!this.klarnaPayments)return n(new ri(ti.PaymentNotInitialized));this.klarnaPayments.authorize({payment_method_category:e},o,e=>e.approved?t(e):e.show_form?n(new Wi):void n(new Xr))})})}}class Dh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Payments)||(yield this.scriptLoader.loadScript("https://x.klarnacdn.net/kp/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Payments))throw new mi;return this.klarnaWindow.Klarna.Payments},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}class Mh{constructor(e){this.requestSender=e}updateClientToken(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this.requestSender.get(i,{timeout:t,headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),params:n})}klarnaOrderInitialization(e,t){return n=this,i=void 0,o=function*(){const n={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{cartId:e,clientToken:t}};yield this.requestSender.put("/api/storefront/initialization/klarna",n)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const zh=fi(e=>{const{getHost:t}=e.getState(),i=n({host:t()});return new kh(e,new Dh(a()),new Mh(i))},[{gateway:"klarna"}]);class xh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return yield this._paymentIntegrationService.submitOrder(e,t),Promise.resolve()},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Nh=fi(e=>new xh(e),[{id:"testgateway"}]);var Rh,Fh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.CREDIT_CARD="credit_card"}(Rh||(Rh={}));const Lh=["klarnapaylater","klarnasliceit"];class jh{constructor(e,t){this.mollieScriptLoader=e,this.paymentIntegrationService=t}initialize(e){return Fh(this,void 0,void 0,function*(){const{mollie:t,methodId:n,gatewayId:i}=e;if(!t)throw new vi('Unable to initialize payment because "options.mollie" argument is not provided.');if(!n||!i)throw new vi('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.');const r=document.querySelectorAll(".mollie-components-controller");F(r,e=>e.remove());const o=this.paymentIntegrationService.getState(),a=o.getStoreConfigOrThrow();this.initializeOptions=t;const s=o.getPaymentMethodOrThrow(n,i),{config:{merchantId:d,testMode:c}}=s;if(this.locale=o.getLocale(),!d)throw new ni(ei.MissingPaymentMethod);return this.isCreditCard(n)&&t.form&&this.shouldShowTSVHostedForm(n,i)?this.hostedForm=yield this.mountCardVerificationfields(t.form):this.isCreditCard(n)&&(this.mollieClient=yield this.loadMollieJs(d,a.storeProfile.storeLanguage,c),this.mountElements()),this.unsubscribe=()=>{if(this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})){const e=document.getElementById(`${i}-${n}-paragraph`);e&&e.remove(),t.disableButton(!1),this.loadPaymentMethodsAllowed(t,n,i)}},this.unsubscribe(),this.loadPaymentMethodsAllowed(t,n,i),Promise.resolve()})}execute(e,t){return Fh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=null==n?void 0:n.paymentData;if(!n||!n.gatewayId||!r)throw new co(["payment","gatewayId","paymentData"]);try{return yield this.paymentIntegrationService.submitOrder(i,t),Nd(r)?yield this.executeWithVaulted(n):this.isCreditCard(n.methodId)?yield this.executeWithCC(n):yield this.executeWithAPM(n)}catch(e){yield this.processAdditionalAction(e)}})}finalize(){return Promise.resolve()}deinitialize(e){if(this.unsubscribe&&this.unsubscribe(),this.hostedForm&&this.hostedForm.detach(),e&&e.methodId&&e.gatewayId&&!this.hostedForm){const t=document.getElementById(`${e.gatewayId}-${e.methodId}`);t&&t.remove()}else e&&e.methodId&&this.isCreditCard(e.methodId)&&this.cardHolderElement&&this.cardNumberElement&&this.verificationCodeElement&&this.expiryDateElement&&(this.cardHolderElement.unmount(),this.cardHolderElement=void 0,this.cardNumberElement.unmount(),this.cardNumberElement=void 0,this.verificationCodeElement.unmount(),this.verificationCodeElement=void 0,this.expiryDateElement.unmount(),this.expiryDateElement=void 0);return this.mollieClient=void 0,Promise.resolve()}executeWithCC(e){return Fh(this,void 0,void 0,function*(){const t=e.paymentData,{shouldSaveInstrument:n=!1,shouldSetAsDefaultInstrument:i=!1}=Bd(t)?t:{},{token:r,error:o}=yield this.getMollieClient().createToken();if(o)return Promise.reject(o);const a={credit_card_token:{token:r},vault_payment_instrument:n,set_as_default_stored_instrument:i,browser_info:ss(),shopper_locale:this.getShopperLocale()};yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:a}}))})}executeWithVaulted(e){return Fh(this,void 0,void 0,function*(){if(this.isHostedPaymentFormEnabled(e.methodId,e.gatewayId)){const t=this.hostedForm;if(!t)throw new ri(ti.PaymentNotInitialized);yield t.validate(),yield t.submit(e),yield this.paymentIntegrationService.loadCurrentOrder()}else yield this.paymentIntegrationService.submitPayment(e)})}executeWithAPM(e){return Fh(this,void 0,void 0,function*(){const t=e.paymentData,n=t&&"issuer"in t?t.issuer:"";yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign(Object.assign({},t),{formattedPayload:{issuer:n,shopper_locale:this.getShopperLocale()}})}))})}isCreditCard(e){return e===Rh.CREDIT_CARD}shouldShowTSVHostedForm(e,t){return this.isHostedPaymentFormEnabled(e,t)&&this.isHostedFieldAvailable()}mountCardVerificationfields(e){return new Promise((t,n)=>Fh(this,void 0,void 0,function*(){try{const n=this.paymentIntegrationService.getState().getStoreConfig(),i=null==n?void 0:n.paymentSettings.bigpayBaseUrl;if(!i)throw new ni(ei.MissingCheckoutConfig);const r=this.paymentIntegrationService.createHostedForm(i,e);yield r.attach(),t(r)}catch(e){n(e)}}))}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:n}=this.paymentIntegrationService.getState();return!0===n(e,t).config.isHostedFormEnabled}isHostedFieldAvailable(){var e;return!!(null===(e=this.getInitializeOptions().form)||void 0===e?void 0:e.fields)}processAdditionalAction(e){if(!pa(e))return Promise.reject(e);if(fe(e.body.errors,{code:"additional_action_required"})){const{additional_action_required:{data:{redirect_url:t}}}=e.body;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ti.PaymentNotInitialized);return this.initializeOptions}loadMollieJs(e,t,n=!1){return this.mollieClient?Promise.resolve(this.mollieClient):this.mollieScriptLoader.load(e,t,n)}getMollieClient(){if(!this.mollieClient)throw new ri(ti.PaymentNotInitialized);return this.mollieClient}getShopperLocale(){if(!this.locale)throw new ri(ti.PaymentNotInitialized);return this.locale}mountElements(){const{containerId:e,cardNumberId:t,cardCvcId:n,cardExpiryId:i,cardHolderId:r,styles:o}=this.getInitializeOptions();let a;e&&(a=document.getElementById(e)),setTimeout(()=>{if(!e||"none"!==(null==a?void 0:a.style.display)){const e=this.getMollieClient();this.cardHolderElement=e.createComponent("cardHolder",{styles:o}),this.cardHolderElement.mount(`#${r}`),this.cardNumberElement=e.createComponent("cardNumber",{styles:o}),this.cardNumberElement.mount(`#${t}`),this.verificationCodeElement=e.createComponent("verificationCode",{styles:o}),this.verificationCodeElement.mount(`#${n}`),this.expiryDateElement=e.createComponent("expiryDate",{styles:o}),this.expiryDateElement.mount(`#${i}`)}},0)}loadPaymentMethodsAllowed(e,t,n){var i;if(Lh.includes(t)){const r=null===(i=this.paymentIntegrationService.getState().getCartOrThrow().lineItems)||void 0===i?void 0:i.digitalItems;if(r&&r.length>0){const{containerId:i}=this.getInitializeOptions();if(i){const r=document.getElementById(i);if(r){const i=document.createElement("p");i.setAttribute("id",`${n}-${t}-paragraph`),e.unsupportedMethodMessage&&(i.innerText=e.unsupportedMethodMessage,r.appendChild(i),e.disableButton(!0))}}}}}}class Bh{constructor(e,t=window){this.scriptLoader=e,this.mollieHostWindow=t}load(e,t,n){return i=this,r=void 0,a=function*(){if(yield this.scriptLoader.loadScript("https://js.mollie.com/v1/mollie.js"),!function(e){return"Mollie"in e}(this.mollieHostWindow))throw new mi;return this.mollieHostWindow.Mollie(e,{locale:t,testmode:n})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}}const Uh=fi(e=>new jh(new Bh(a()),e),[{gateway:"mollie"},{gateway:"mollie",id:"applepay"}]);var qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Vh="moneris-payment-iframe";class Gh{constructor(e){this.paymentIntegrationService=e}initialize(e){return qh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{moneris:n,methodId:i}=e;if(!i)throw new vi('Unable to initialize payment because "methodId" argument is not provided.');if(!n)throw new vi('Unable to initialize payment because "options.moneris" argument is not provided.');this.initializeOptions=n;const{config:r,initializationData:o}=t.getPaymentMethodOrThrow(i);if(!(null==o?void 0:o.profileId))throw new ni(ei.MissingPaymentMethod);return n.form&&this.shouldShowTSVHostedForm(i)&&(this.hostedForm=yield this.mountCardVerificationfields(n.form)),this.iframe||(this.iframe=this.createIframe(n.containerId,o,!!r.testMode)),Promise.resolve()})}execute(e,t){return qh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{isStoreCreditApplied:r}=this.paymentIntegrationService.getState().getCheckoutOrThrow();if(r&&(yield this.paymentIntegrationService.applyStoreCredit(r)),yield this.paymentIntegrationService.submitOrder(i,t),!n.paymentData||!Nd(n.paymentData))return this.executeWithCC(n);yield this.executeWithVaulted(n)})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this.hostedForm&&this.hostedForm.detach(),this.windowEventListener&&(window.removeEventListener("message",this.windowEventListener),this.windowEventListener=void 0),this.iframe&&this.iframe.parentNode&&(this.iframe.parentNode.removeChild(this.iframe),this.iframe=void 0),Promise.resolve()}executeWithCC(e){return qh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId).config.testMode,n=e.paymentData||{},i=Bd(n)?n:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o}=i,a=yield new Promise((e,n)=>{if(!this.iframe)throw new ri(ti.PaymentNotInitialized);const i=this.iframe.contentWindow;if(null===i)throw new ri(ti.PaymentNotInitialized);i.postMessage("tokenize",this.monerisURL(!!t)),this.windowEventListener=i=>{if("string"==typeof i.data&&i.origin===`https://${t?"esqa":"www3"}.moneris.com`)try{e(this.handleMonerisResponse(i))}catch(e){n(e)}},window.addEventListener("message",this.windowEventListener)});void 0!==a&&(yield this.paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:{nonce:a,shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o}}))})}executeWithVaulted(e){return qh(this,void 0,void 0,function*(){if(this.hostedForm){const t=this.hostedForm;return yield t.validate(),yield t.submit(e),this.paymentIntegrationService.loadCurrentOrder()}return this.paymentIntegrationService.submitPayment(e)})}shouldShowTSVHostedForm(e){return this.isHostedPaymentFormEnabled(e)&&this.isHostedFieldAvailable()}isHostedPaymentFormEnabled(e){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return Boolean(t.config.isHostedFormEnabled)}isHostedFieldAvailable(){var e;const t=this.getInitializeOptions(),n=ue(null===(e=t.form)||void 0===e?void 0:e.fields,$);return!$(n)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ti.PaymentNotInitialized);return this.initializeOptions}mountCardVerificationfields(e){var t;return qh(this,void 0,void 0,function*(){const n=null===(t=this.paymentIntegrationService.getState().getStoreConfig())||void 0===t?void 0:t.paymentSettings.bigpayBaseUrl;if(!n)throw new ni(ei.MissingCheckoutConfig);const i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}createIframe(e,t,n,i){const r=document.getElementById(e);if(!r)throw new vi("Unable to create iframe without valid container ID.");const o=document.createElement("iframe"),a={id:t.profileId,pmmsg:!0,display_labels:1,enable_exp:1,enable_cvd:1,css_body:(null==i?void 0:i.cssBody)||"font-family: Arial, Helvetica,sans-serif;background: transparent;",css_textbox:(null==i?void 0:i.cssTextbox)||"border-radius:4px;border: 2px solid rgb(00,00,00);width: 100%;font-weight: 600;padding: 8px 8px;outline: 0;",css_textbox_pan:(null==i?void 0:i.cssTextboxCardNumber)||"width: 240px;",css_textbox_exp:(null==i?void 0:i.cssTextboxExpiryDate)||"margin-bottom: 0;width: calc(30% - 12px);",css_textbox_cvd:(null==i?void 0:i.cssTextboxCVV)||"margin-bottom: 0;width: calc(30% - 12px);",css_input_label:(null==i?void 0:i.cssInputLabel)||"font-size: 10px;position: relative;top: 8px;left: 6px;background: rgb(255,255,255);padding: 3px 2px;color: rgb(66,66,66);font-weight: 600;z-index: 2;",pan_label:t.creditCardLabel||"Credit Card Number",exp_label:t.expiryDateLabel||"Expiration",cvd_label:t.cvdLabel||"CVD"},s=oe(a,(e,t)=>`${t}=${e}`).join("&");return o.width="100%",o.height="100%",o.name=Vh,o.id=Vh,o.style.border="none",o.src=`${this.monerisURL(n)}?${s}`,o.allow="payment",r.appendChild(o),o}handleMonerisResponse(e){const t=JSON.parse(e.data);if("001"!==t.responseCode[0])throw new Error(t.errorMessage);return t.dataKey}monerisURL(e){return`https://${e?"esqa":"www3"}.moneris.com/HPPtoken/index.php`}}const Hh=fi(e=>new Gh(e),[{id:"moneris"}]);class Wh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return yield this._paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:e.payment?{methodId:e.payment.methodId}:void 0}),t),Promise.resolve()},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const $h=fi(e=>new Wh(e),[{type:"PAYMENT_TYPE_OFFLINE"}]);var Yh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Kh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return Yh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=this._shouldSubmitFullPayload(n)?e:i,o=n&&n.paymentData,a=o&&Nd(o)&&o.instrumentId||void 0,s=o&&Bd(o)&&o.shouldSaveInstrument||void 0,d=o&&Bd(o)&&o.shouldSetAsDefaultInstrument||void 0;if(!n)throw new co(["payment"]);const{methodId:c,gatewayId:l}=n;yield this._paymentIntegrationService.submitOrder(r,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:c,gatewayId:l,instrumentId:a,shouldSaveInstrument:s,shouldSetAsDefaultInstrument:d})})}finalize(e){return Yh(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),n=t.getOrder(),i=t.getPaymentStatus();if(!n||i!==dl.ACKNOWLEDGE&&i!==dl.FINALIZE)return Promise.reject(new Cd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_shouldSubmitFullPayload(e){return!!e&&("adyen"===e.gatewayId||"barclaycard"===e.gatewayId)}}const Jh=fi(e=>new Kh(e),[{type:"PAYMENT_TYPE_HOSTED"}]),Zh=function({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};var Qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xh{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.payPalSdkScriptLoader=n,this.loadingIndicator=i}initialize(e){var t;return Qh(this,void 0,void 0,function*(){const{methodId:n,paypalcommerce:i}=e||{};if(this.paypalcommerce=i,!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{container:a,bannerContainerId:s}=i,{orderId:d,paypalBNPLConfiguration:c=[],isPayPalCreditAvailable:l}=o.initializationData||{};if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=null==c?void 0:c.find(({id:e})=>"checkout"===e);if(l||!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(o,r.getCartOrThrow().currency.code,r.getLocale());return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,s,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}d?this.orderId=null===(t=o.initializationData)||void 0===t?void 0:t.orderId:(this.loadingIndicatorContainer=null==a?void 0:a.split("#")[1],yield this.paypalIntegrationService.loadPayPalSdk(n),i.onInit&&"function"==typeof i.onInit&&i.onInit(()=>this.renderButton(n,i)),(void 0===i.shouldRenderPayPalButtonOnInitialization||i.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(n,i))})}execute(e,t){var n,i;return Qh(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{onError:a}=this.paypalcommerce||{};if(!r)throw new co(["payment"]);const{methodId:s,paymentData:d}=r;if(this.isPayPalVaultedInstrumentPaymentData(d)&&!this.orderId&&(this.orderId=yield this.createOrder()),!this.orderId)throw new Xr;const c=this.isPayPalVaultedInstrumentPaymentData(d)?this.prepareVaultedInstrumentPaymentPayload(s,this.orderId,d):this.preparePaymentPayload(s,this.orderId,d);try{yield this.paymentIntegrationService.submitOrder(o,t),yield this.paymentIntegrationService.submitPayment(c)}catch(e){if(function(e){var t;return pa(e)&&"offsite_redirect"===(null===(t=e.body.additional_action_required)||void 0===t?void 0:t.type)}(e)){const t=null===(i=null===(n=e.body.additional_action_required)||void 0===n?void 0:n.data)||void 0===i?void 0:i.redirect_url;return new Promise(()=>window.location.replace(t))}return this.isProviderError(e)&&(yield this.paypalIntegrationService.loadPayPalSdk(r.methodId),yield new Promise((e,t)=>{var n;this.paypalcommerce&&(null===(n=this.paypalButton)||void 0===n||n.close(),this.renderButton(r.methodId,this.paypalcommerce),this.handleError(new Error("INSTRUMENT_DECLINED"),a)),t()})),this.handleError(e,a),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=Bd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.paypalIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new vi('Unable to initialize payment because "container" argument is not provided.');const y=this.getSmartButtonContainerId(l);if(!document.getElementById(y))throw new vi(`Unable to initialize payment because element with id ${y} does not exist.`);const g=Object.assign(Object.assign({},this.isPaypalCommerceAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.paypalIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(g),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isPaypalCommerceAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return Qh(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return Qh(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.paypalIntegrationService.createOrder("paypalcommercecheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.paypalcommerce||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&Nd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&Nd(e)&&Bd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const ep=fi(e=>new Xh(e,As(e),new ws(a()),new fd({containerStyles:Ka})),[{id:"paypalcommerce"}]);var tp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class np{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.loadingIndicator=n,this.payPalSdkScriptLoader=i}initialize(e){return tp(this,void 0,void 0,function*(){const{methodId:t,paypalcommerce:n,paypalcommercecredit:i}=e||{},r=i||n;if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const o=this.paymentIntegrationService.getState(),a=o.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:s=[],orderId:d}=a.initializationData||{},{bannerContainerId:c,container:l}=r;if(void 0!==c){if(!document.getElementById(c))return void console.error("Unable to create banner without valid banner container ID.");const e=s&&s.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(a,o.getCartOrThrow().currency.code,o.getLocale());return this.renderMessages(t,c,e)}d?this.orderId=d:(yield this.paypalIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==l?void 0:l.split("#")[1],this.renderButton(t,r))})}execute(e,t){return tp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);if(!this.orderId)throw new Xr;yield this.paymentIntegrationService.submitOrder(i,t),yield this.paypalIntegrationService.submitPayment(n.methodId,this.orderId)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){if(!(null==t?void 0:t.container))throw new vi('Unable to initialize payment because "container" argument is not provided.');const n=this.paypalIntegrationService.getPayPalSdkOrThrow(),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=i.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u=[n.FUNDING.PAYLATER,n.FUNDING.CREDIT];let h=!1;u.forEach(e=>{if(h)return;const t={fundingSource:e,style:this.paypalIntegrationService.getValidButtonStyle(o),createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercecreditcheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(t),this.paypalButton.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.paypalButton.isEligible()&&e===n.FUNDING.CREDIT)throw new _i(`PayPal ${e} is not available for your region. Please use PayPal Checkout instead.`);d&&"function"==typeof d&&d(),this.paypalButton.render(a),h=!0}})}handleClick(e,t){return tp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;if(t&&"function"==typeof t)return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}}const ip=fi(e=>new np(e,As(e),new fd({containerStyles:Ka}),Cs()),[{id:"paypalcommercecredit"}]);var rp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class op{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return rp(this,void 0,void 0,function*(){const{methodId:i,paypalcommerce:r,paypalcommercevenmo:o}=e||{},a=o||r;if(!i)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!a)throw new vi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=s.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=s.initializationData)||void 0===n?void 0:n.orderId:(yield this.paypalCommerceIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=a.container.split("#")[1],this.renderButton(i,a))})}execute(e,t){return rp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);if(!this.orderId)throw new Xr;yield this.paymentIntegrationService.submitOrder(i,t),yield this.paypalCommerceIntegrationService.submitPayment(n.methodId,this.orderId)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){const n=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=i.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u={fundingSource:n.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o),createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new _i("PayPal Venmo is not available for your region. Please use PayPal Checkout instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return rp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const ap=fi(e=>new op(e,$s(e),new fd({styles:{backgroundColor:"black"}})),[{id:"paypalcommercevenmo"}]),sp={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};var dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cp{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalSdkScriptLoader=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isOrderApprovedProcessing=!1}initialize(e){return dp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerce:i,paypalcommercealternativemethods:r}=e,o=r||i;if(this.paypalcommercealternativemethods=r,!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!o)throw new vi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');const a=this.paymentIntegrationService.getState(),s=a.getPaymentMethodOrThrow(n,t),{orderId:d,shouldRenderFields:c}=s.initializationData||{},l=a.getStoreConfigOrThrow().checkoutSettings.features;this.isOrderApprovedProcessing=Ci(l,"PAYPAL-5431.order_approved_processing",!1),d?this.orderId=d:(this.paypalApms=yield this.paypalSdkScriptLoader.getPayPalApmsSdk(s,a.getCartOrThrow().currency.code,a.getLocale()),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(n,t,o),c&&this.renderFields(n,o))})}execute(e,t){return dp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{methodId:r,gatewayId:o}=n;if(!this.orderId)throw new Xr;this.isOrderApprovedProcessing||"ideal"!==r||(yield new Promise((e,t)=>{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)&&(r!==js.IDEAL||this.isOrderApprovedProcessing)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.paypalCommerceIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isOrderApprovedProcessing||this.resetPollingMechanism(),null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return dp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceIntegrationService.getOrderStatus(null!=i?i:"paypalcommerce"),o=r===Bs.Approved,a=r===Bs.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,n,i);yield this.reinitializeStrategy({methodId:e,gatewayId:i,paypalcommercealternativemethods:this.paypalcommercealternativemethods}),this.handleError(new wc)}catch(e){n()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}reinitializeStrategy(e){return dp(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}handleError(e){const{onError:t}=this.paypalcommercealternativemethods||{};this.isOrderApprovedProcessing||this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderButton(e,t,n){const i=this.getPaypalAmpsSdkOrThrow(),r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t),{buttonStyle:o}=r.initializationData||{},{container:a,onError:s,onRenderButton:d,submitForm:c}=n,l={fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o),onInit:(e,t)=>n.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deinitializePollingMechanism()},onError:e=>{this.deinitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>dp(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.paypalButton=i.Buttons(l),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}onCreateOrder(e,t,n){var i;return dp(this,void 0,void 0,function*(){const{onValidate:r}=n;yield r(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const o=yield this.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethodscheckout");if(this.isNonInstantPaymentMethod(e)&&(e===js.IDEAL&&this.isOrderApprovedProcessing||e===js.OXXO)){const n={useStoreCredit:!1},r={params:{methodId:e,gatewayId:t}};if(yield this.paymentIntegrationService.submitOrder(n,r),e===js.IDEAL){const t=this.paymentIntegrationService.getState(),n=null===(i=t.getOrder())||void 0===i?void 0:i.orderId;yield this.paypalCommerceIntegrationService.updateOrder("paypalcommercealternativemethods",e,n)}yield this.paypalCommerceIntegrationService.submitPayment(e,o,t)}return o})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new vi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in js}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const lp=fi(e=>new cp(e,As(e),Cs(),new fd({containerStyles:sp})),[{gateway:"paypalcommercealternativemethods"}]);var up=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hp{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){return up(this,void 0,void 0,function*(){const{methodId:t,paypalcommercecreditcards:n,paypalcommerce:i}=e,r=n||i,{form:o,onCreditCardFieldsRenderingError:a,onLoadComplete:s}=r||{};if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new vi('Unable to proceed because "options.paypalcommercecreditcards.form" argument is not provided.');this.hostedFormOptions=o,this.isCreditCardForm=Ac(o.fields),this.isCreditCardVaultedForm=Tc(o.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.paypalIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(o,a)),null==s||s(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return up(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{methodId:r,paymentData:o}=n||{};if(!n||!r)throw new co(["payment"]);if(this.executionPaymentData=o,this.isCreditCardForm||this.isCreditCardVaultedForm)yield this.validateHostedFormOrThrow(),yield this.submitHostedForm();else{const{orderId:e}=yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",this.getInstrumentParams());this.returnedOrderId=e}const a=this.preparePaymentPayload(r,o,this.returnedOrderId,this.returnedVaultedToken);yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e,t,n,i;return up(this,void 0,void 0,function*(){return yield null===(e=this.cvvField)||void 0===e?void 0:e.close(),yield null===(t=this.expiryField)||void 0===t?void 0:t.close(),yield null===(n=this.numberField)||void 0===n?void 0:n.close(),yield null===(i=this.nameField)||void 0===i?void 0:i.close(),Promise.resolve()})}preparePaymentPayload(e,t,n,i){const{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=Bd(t)?t:{},a=t&&Nd(t)?t.instrumentId:void 0,s=ue({verification_nonce:i,token:a},J);return{methodId:e,paymentData:{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o,instrumentId:a,formattedPayload:Object.assign(Object.assign({},i||a?{bigpay_token:s}:{}),n?{card_with_order:{order_id:n}}:{})}}}initializeFields(e,t){return up(this,void 0,void 0,function*(){const{fields:n,styles:i}=e,r=this.paypalIntegrationService.getPayPalSdkOrThrow(),o=this.getExecuteCallback(n),a=Object.assign({style:this.getInputStyles(i),onApprove:({orderID:e,vaultSetupToken:t,liabilityShift:n})=>{if(n===xs.No||n===xs.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ti.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>up(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>up(this,void 0,void 0,function*(){const{orderId:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return up(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return up(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(Bd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(Nd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return up(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return up(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ti.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isPayPalCommerceAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return up(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(i,n.currency.code,n.id,t.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const pp=fi(e=>new hp(e,As(e),Cs(),nd()),[{id:"paypalcommercecreditcards"}]);var mp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class yp{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.paypalCommerceService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return mp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerceratepay:i}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.paypalcommerceratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new vi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new vi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new vi("Unable to initialize payment because merchantId argument is not provided.");this.paypalcommerceratepay=i,yield this.paypalCommerceService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return mp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{getFieldsValues:r}=this.paypalcommerceratepay||{};if(!n)throw new co(["payment"]);if(!r||"function"!=typeof r)throw new vi('Unable to initialize payment because "options.getFieldsValues" argument is not provided.');this.toggleLoadingIndicator(!0);try{const e=yield this.paypalCommerceService.createOrder("paypalcommercealternativemethodscheckout",{metadataId:this.guid}),{ratepayBirthDate:o,ratepayPhoneNumber:a,ratepayPhoneCountryCode:s}=r(),d={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:n.methodId,rate_pay:{birth_date:this.normalizeDate(o),phone:{national_number:a,country_code:s.split("+")[1]}},paypal_account:{order_id:e}}};return yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:d}),yield new Promise((e,t)=>{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.paypalcommerceratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.paypalCommerceService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new vi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.paypalcommerceratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return mp(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return mp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceService.getOrderStatus("paypalcommercealternativemethods",{params:{useMetadata:!0}}),o=r===Ss.PollingStop,a=r===Ss.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,n,i);yield this.reinitializeStrategy({methodId:e,gatewayId:i,paypalcommerceratepay:this.paypalcommerceratepay}),this.handleError(new wc)}catch(e){this.handleError(e),n()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const gp=fi(e=>new yp(e,As(e),new fd({containerStyles:Object.assign(Object.assign({},Ka),{position:"fixed"})})),[{gateway:"paypalcommercealternativemethods",id:"ratepay"}]);function fp(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var vp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _p{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalCommerceRequestSender=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){var t,n;return vp(this,void 0,void 0,function*(){const{methodId:i,paypalcommercefastlane:r}=e;if(this.methodId=i,this.paypalcommercefastlane=r,!i)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.paypalcommercefastlane" argument is not provided.');if(!r.onInit||"function"!=typeof r.onInit)throw new vi('Unable to initialize payment because "options.paypalcommercefastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new vi('Unable to initialize payment because "options.paypalcommercefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(s,a.currency.code,a.id,o.getLocale());const l=rd(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.paypalFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return vp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{paymentData:r,methodId:o}=n,a=r&&Nd(r);try{yield this.paymentIntegrationService.submitOrder(i,t);const e=a?yield this.prepareVaultedInstrumentPaymentPayload(o,r):yield this.preparePaymentPayload(o,r);yield this.paymentIntegrationService.submitPayment(e),this.paypalFastlaneUtils.removeStorageSessionId()}catch(e){if(function(e){return"object"==typeof e&&null!==e&&"message"in e&&"response"in e&&"body"in e.response&&"name"in e.response.body}(e)&&"INVALID_REQUEST"===e.response.body.name){const e={translationKey:"payment.errors.invalid_request_error"};return this.handleError(e),Promise.reject()}if(e instanceof Error&&"FastlaneError"!==e.name)throw e;return Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return vp(this,void 0,void 0,function*(){return Promise.resolve()})}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getCustomerOrThrow(),i=e.getPaymentProviderCustomer(),r=fp(i)?i:{},o=this.paypalFastlaneUtils.getStorageSessionId();return!(!n.isGuest||(null==r?void 0:r.authenticationState)===vs.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}runPayPalAuthenticationFlowOrThrow(e){return vp(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.paypalFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(a),{authenticationState:d,addresses:c,instruments:l}=this.paypalFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,s);yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:d,addresses:c,instruments:l}),s.authenticationState===vs.CANCELED?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(n.id)}catch(e){}})}initializePayPalPaymentComponent(){return vp(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),t=e.phone,n=`${e.firstName} ${e.lastName}`.trim(),i=this.paypalFastlaneUtils.getPayPalFastlaneOrThrow(),r={fields:Object.assign({cardholderName:{prefill:n,enabled:!0}},t&&{phoneNumber:{prefill:t}})};this.paypalComponentMethods=yield i.FastlaneCardComponent(r)})}renderPayPalPaymentComponent(e){const t=this.getPayPalComponentMethodsOrThrow();if(!e)throw new vi('Unable to render card component because "container" argument is not provided.');t.render(e)}getPayPalComponentMethodsOrThrow(){if(!this.paypalComponentMethods)throw new mi;return this.paypalComponentMethods}prepareVaultedInstrumentPaymentPayload(e,t){return vp(this,void 0,void 0,function*(){const{instrumentId:n}=t,i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).config.is3dsEnabled?yield this.get3DSNonce(n):n;return yield this.createOrder(i),{methodId:e,paymentData:{formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:i}}}}})}preparePaymentPayload(e,t){return vp(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getBillingAddressOrThrow(),r=n.getPaymentMethodOrThrow(e),o=`${i.firstName} ${i.lastName}`.trim(),{getPaymentToken:a}=this.getPayPalComponentMethodsOrThrow(),{id:s}=yield a({name:{fullName:o},billingAddress:this.paypalFastlaneUtils.mapBcToPayPalAddress(i)}),d=r.config.is3dsEnabled?yield this.get3DSNonce(s):s;yield this.createOrder(d);const{shouldSaveInstrument:c=!1,shouldSetAsDefaultInstrument:l=!1}=Bd(t)?t:{};return{methodId:e,paymentData:Object.assign(Object.assign({},t),{shouldSaveInstrument:c,shouldSetAsDefaultInstrument:l,formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:d}}})}})}createOrder(e){return vp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getCartOrThrow().id;if(this.methodId){const{orderId:n}=yield this.paypalCommerceRequestSender.createOrder(this.methodId,{cartId:t,fastlaneToken:e});this.orderId=n}})}get3DSNonce(e){var t;return vp(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getCartOrThrow(),r=n.getOrderOrThrow(),o=n.getStoreConfigOrThrow().links.checkoutLink,a=null===(t=this.paypalFastlaneSdk)||void 0===t?void 0:t.ThreeDomainSecureClient;if(!a)throw new mi;const s={amount:r.orderAmount.toFixed(2),currency:i.currency.code,nonce:e,threeDSRequested:this.threeDSVerificationMethod===hs.Always,transactionContext:{experience_context:{locale:"en-US",return_url:o,cancel_url:o}}},d=yield a.isEligible(s);if(this.threeDSVerificationMethod===hs.Always&&!d)throw new Xr;if(d){const{liabilityShift:e,authenticationState:t,nonce:n}=yield a.show();if(e===xs.No||e===xs.Unknown||t===ps.Errored||t===ps.Cancelled)throw new Xr;if(t===ps.Succeeded&&[xs.Yes,xs.Possible].includes(e))return n;throw new Xr}return e})}handlePayPalStoredInstrumentChange(e){return vp(this,void 0,void 0,function*(){const t=this.paypalFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:n,selectedCard:i}=yield t.profile.showCardSelector();if(n){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),n=fp(t)?t:{},r=this.paypalFastlaneUtils.mapPayPalToBcInstrument(e,i)[0];return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},n),{instruments:[r]})),r}})}handleError(e){var t;(null===(t=this.paypalcommercefastlane)||void 0===t?void 0:t.onError)&&"function"==typeof this.paypalcommercefastlane.onError&&this.paypalcommercefastlane.onError(e)}}const Sp=fi(e=>{const{getHost:t}=e.getState();return new _p(e,new Gs(n({host:t()})),Cs(),nd())},[{id:"paypalcommerceacceleratedcheckout"}]);var Ip,wp,Cp,bp,Pp,Op;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(Ip||(Ip={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(wp||(wp={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(Cp||(Cp={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(bp||(bp={})),function(e){e.PILL="pill",e.RECT="rect"}(Pp||(Pp={})),function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(Op||(Op={}));var Ep=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ap{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.useRedirectFlow=!1,this.window=window}initialize(e){return Ep(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();this.paymentMethod=t.getPaymentMethodOrThrow(e.methodId),this.useRedirectFlow=!0===(e.paypalexpress&&e.paypalexpress.useRedirectFlow);const n=this.paymentMethod.config.merchantId;if(!this.isInContextEnabled()||!n)throw new ni(ei.MissingPaymentMethod);const i=yield this.scriptLoader.loadPaypalSDK();this.paypalSdk=i,this.paypalSdk.checkout.setup(n,{button:"paypal-button",environment:this.paymentMethod.config.testMode?"sandbox":"production"})})}deinitialize(){return this.isInContextEnabled()&&this.paypalSdk&&(this.paypalSdk.checkout.closeFlow(),this.paypalSdk=void 0),Promise.resolve()}execute(e,t){return Ep(this,void 0,void 0,function*(){let n,i;const r=this.paypalSdk;if(!this.isAcknowledgedOrFinalized()){if(!this.isInContextEnabled()||this.useRedirectFlow)return n=yield this.paymentIntegrationService.submitOrder(e,t),i=n.getPaymentRedirectUrl(),i&&this.window.top&&(this.window.top.location.href=i),new Promise(ce);if(!r)throw new ri(ti.PaymentNotInitialized);r.checkout.initXO();try{n=yield this.paymentIntegrationService.submitOrder(e,t)}catch(e){return r.checkout.closeFlow(),Promise.reject(e)}return i=n.getPaymentRedirectUrl(),i&&r.checkout.startFlow(i),new Promise(ce)}yield this.paymentIntegrationService.submitOrder(e,t)})}finalize(e){return Ep(this,void 0,void 0,function*(){return this.paymentIntegrationService.getState().getOrder()&&this.isAcknowledgedOrFinalized()?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}isAcknowledgedOrFinalized(){const e=this.paymentIntegrationService.getState();return e.getPaymentStatus()===Op.ACKNOWLEDGE||e.getPaymentStatus()===Op.FINALIZE}isInContextEnabled(){return!(!this.paymentMethod||!this.paymentMethod.config.merchantId)}}class Tp{constructor(e){this.scriptLoader=e,this.window=window}loadPaypalSDK(e=""){return t=this,n=void 0,r=function*(){const t=Object.assign({async:!0,attributes:{"data-merchant-id":e}},e&&{attributes:{"data-merchant-id":e}});if(yield this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",t),!this.window.paypal)throw new mi;return this.window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const kp=fi(e=>new Ap(e,new Tp(a())),[{id:"paypalexpress",type:"PAYMENT_TYPE_HOSTED"},{id:"paypalexpresscredit",type:"PAYMENT_TYPE_HOSTED"}]);var Dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mp extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Dp(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);n.config.is3dsEnabled&&(yield this.threeDSecureFlow.prepare(n))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Dp(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,r=this.paymentIntegrationService.getState();return r.getPaymentStatus()===dl.ACKNOWLEDGE?(yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:{methodId:i}}),t),Promise.resolve()):r.getPaymentMethodOrThrow(i).config.is3dsEnabled?this.threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const zp=fi(e=>new Mp(e,new Au(e,new Fu(new Lu(a())))),[{id:"paypal"}]);class xp extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this._formPoster=t}execute(e,t){const{payment:n}=e;if(!n)throw new ri(ti.PaymentNotInitialized);const{paymentData:i}=n;if(!i)throw new ni(ei.MissingPayment);if(this._isThreeDSTwoExperimentOn()){const t=Object.assign(Object.assign({},i),{browser_info:ss()});e.payment&&(e.payment.paymentData=t)}return super.execute(e,t).catch(e=>pa(e)&&fe(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{let t;t=this._isThreeDSTwoExperimentOn()&&!e.body.three_ds_result.merchant_data?{creq:e.body.three_ds_result.payer_auth_request}:{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data},this._formPoster.postForm(e.body.three_ds_result.acs_url,t,void 0,"_top")}):Promise.reject(e))}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),super.finalize()}_isThreeDSTwoExperimentOn(){return!0===this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features["INT-4994.Opayo_3DS2"]}}const Np=fi(e=>new xp(e,Ee()),[{id:"sagepay"}]);class Rp{constructor(e,t){this._formPoster=e,this._paymentIntegrationService=t}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))}catch(e){if(!pa(e)||"object"!=typeof(o=e.body)||null===o||!("additional_action_required"in o)||!this._isAdditionalActionRequired(e.body))return Promise.reject(e);const{body:{additional_action_required:{data:{redirect_url:t}}}}=e;return new Promise(()=>{this.redirectUrl(t)})}var o},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}redirectUrl(e){return this._formPoster.postForm(e,{})}_isAdditionalActionRequired(e){const{additional_action_required:t,status:n}=e;return"additional_action_required"===n&&t&&"offsite_redirect"===t.type}}class Fp extends Rp{redirectUrl(e){window.location.replace(e)}}const Lp=fi(e=>new Fp(Ee(),e),[{id:"sezzle"}]);var jp;!function(e){e.CHARGE="CHARGE",e.STORE="STORE"}(jp||(jp={}));var Bp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Up{constructor(e,t){this._scriptLoader=e,this._paymentIntegrationService=t}initialize({testMode:e,applicationId:t,locationId:n}){return Bp(this,void 0,void 0,function*(){const i=yield this._scriptLoader.load(e);this._payments=i.payments(t,n)})}deinitialize(){return Bp(this,void 0,void 0,function*(){this._formValidationSubscription&&this._formValidationSubscription.unsubscribe(),this._card&&(yield this._card.destroy()),this._formValidationSubscription=void 0,this._card=void 0,this._payments=void 0})}initializeCard({containerId:e,style:t,onValidationChange:n}){return Bp(this,void 0,void 0,function*(){const{postalCode:i}=this._paymentIntegrationService.getState().getBillingAddress()||{};this._card=yield this._getPayments().card(),yield this._card.attach(`#${e}`);try{yield this._card.configure({postalCode:i,style:t})}catch(e){}n&&(this._formValidationSubscription=this._subscribeToFormValidation(this._card,n))})}tokenize(){return Bp(this,void 0,void 0,function*(){const e=yield this._getCard().tokenize();if("OK"!==e.status||!e.token){let t=`Tokenization failed with status: ${e.status}`;throw e.errors&&(t+=` and errors: ${JSON.stringify(e.errors)}`),new Sh("payment.errors.card_error","SquareV2TokenizationError",t)}return e.token})}verifyBuyer(e,t){return Bp(this,void 0,void 0,function*(){return t===jp.CHARGE?this._chargeVerifyBuyer(e):this._storeVerifyBuyer(e)})}_getPayments(){return ii(this._payments,()=>new ri(ti.PaymentNotInitialized))}_subscribeToFormValidation(e,t){const n=["cardNumber","cvv"],i=new Set(n),r=["focusClassAdded","focusClassRemoved","errorClassAdded","errorClassRemoved","cardBrandChanged","postalCodeChanged"].map(t=>S(e,t));return I(...r).pipe(T(e=>{const{detail:{field:t,currentState:{isCompletelyValid:r}}}=e;return n.includes(t)&&i[r?"delete":"add"](t),0===i.size}),E()).subscribe(t)}_getCard(){return ii(this._card,()=>new ri(ti.PaymentNotInitialized))}_mapToSquareBillingContact({firstName:e,lastName:t,address1:n,address2:i,city:r,stateOrProvinceCode:o,postalCode:a,countryCode:s,email:d,phone:c}){return{givenName:e,familyName:t,addressLines:[n,i],city:r,state:o,postalCode:a,countryCode:s,email:d,phone:c}}_chargeVerifyBuyer(e){return Bp(this,void 0,void 0,function*(){const{getCheckoutOrThrow:t,getBillingAddressOrThrow:n}=this._paymentIntegrationService.getState(),{outstandingBalance:i,cart:r}=t(),o={amount:i.toString(),billingContact:this._mapToSquareBillingContact(n()),currencyCode:r.currency.code,intent:jp.CHARGE},a=yield this._getPayments().verifyBuyer(e,o);return a?a.token:""})}_storeVerifyBuyer(e){return Bp(this,void 0,void 0,function*(){const{getBillingAddressOrThrow:t}=this._paymentIntegrationService.getState(),n={billingContact:this._mapToSquareBillingContact(t()),intent:jp.STORE},i=yield this._getPayments().verifyBuyer(e,n);return i?i.token:""})}}var qp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vp{constructor(e,t){this._paymentIntegrationService=e,this._squareV2PaymentProcessor=t}initialize(e){var t;return qp(this,void 0,void 0,function*(){if(!(null===(t=null==e?void 0:e.squarev2)||void 0===t?void 0:t.containerId))throw new vi('Unable to proceed because "containerId" argument is not provided.');const{methodId:n,squarev2:i}=e,{config:{testMode:r},initializationData:o}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{applicationId:a,locationId:s}=o||{};if(!a)throw new Xr;yield this._squareV2PaymentProcessor.initialize({applicationId:a,locationId:s,testMode:r}),yield this._squareV2PaymentProcessor.initializeCard(i)})}execute({payment:e}){return qp(this,void 0,void 0,function*(){if(!e)throw new co(["payment"]);const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r}=Bd(n)?n:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};yield this._paymentIntegrationService.submitOrder();const o=n&&Nd(n)?yield this._getVaultedInstrumentPayload(t,n):yield this._getCardPayload(t,i);yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:Object.assign(Object.assign({},o),{vault_payment_instrument:i||!1,set_as_default_stored_instrument:r||!1})}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._squareV2PaymentProcessor.deinitialize()}shouldVerify(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return e["PROJECT-3828.add_3ds_support_on_squarev2"]}_getCardPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),r=yield this._squareV2PaymentProcessor.tokenize();if(i&&"isSquareV2ApiV2Enabled"in i?!i.isSquareV2ApiV2Enabled:!this.shouldVerify())return{credit_card_token:{token:r}};let o={nonce:r,token:yield this._squareV2PaymentProcessor.verifyBuyer(r,jp.CHARGE)};if(t){const e=yield this._squareV2PaymentProcessor.tokenize();o=Object.assign(Object.assign({},o),{store_card_nonce:e,store_card_token:yield this._squareV2PaymentProcessor.verifyBuyer(e,jp.STORE)})}return{credit_card_token:{token:JSON.stringify(o)}}})}_getVaultedInstrumentPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),{instrumentId:r}=t,o=(i&&"isSquareV2ApiV2Enabled"in i?i.isSquareV2ApiV2Enabled:this.shouldVerify())?yield this._squareV2PaymentProcessor.verifyBuyer(yield this._getSquareCardIdOrThrow(e,r),jp.CHARGE):void 0;return{bigpay_token:Object.assign({token:r},o&&{three_d_secure:{token:o}})}})}_getSquareCardIdOrThrow(e,t){return qp(this,void 0,void 0,function*(){const n=yield this._paymentIntegrationService.loadPaymentMethod(e,{params:{method:e,bigpayToken:t}}),{initializationData:i}=n.getPaymentMethodOrThrow(e),{cardId:r}=i||{};if(!r)throw new co(["cardId"]);return r})}}var Gp;!function(e){e.LIVE="https://web.squarecdn.com/v1/square.js",e.SANDBOX="https://sandbox.web.squarecdn.com/v1/square.js"}(Gp||(Gp={}));class Hp{constructor(e){this._scriptLoader=e}load(e=!1){return t=this,n=void 0,r=function*(){return yield this._scriptLoader.loadScript(e?Gp.SANDBOX:Gp.LIVE),function(e){if(!function(e){return"Square"in e}(e))throw new mi}(window),window.Square},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const Wp=fi(e=>new Vp(e,new Up(new Hp(a()),e)),[{id:"squarev2"}]);function $p(e){return null!==e&&"object"==typeof e&&"cardNumberElementOptions"in e&&"cardCvcElementOptions"in e&&"cardExpiryElementOptions"in e&&void 0!==e.cardNumberElementOptions&&void 0!==e.cardCvcElementOptions&&void 0!==e.cardExpiryElementOptions}var Yp,Kp,Jp,Zp;!function(e){e.Solid="solid",e.Default="default"}(Yp||(Yp={})),function(e){e.Alipay="alipay",e.CardCvc="cardCvc",e.CardExpiry="cardExpiry",e.CardNumber="cardNumber",e.CreditCard="card",e.IDEAL="idealBank",e.Sepa="iban"}(Kp||(Kp={})),function(e){e.Alipay="alipay",e.CreditCard="card",e.IDEAL="ideal",e.Sepa="sepa_debit"}(Jp||(Jp={})),function(e){e.AuthFailure="auth_failure"}(Zp||(Zp={}));class Qp extends Xn{constructor(e){super(e===Zp.AuthFailure?"User did not authenticate":"There was an error while processing your payment. Please try again or contact us."),this.type="stripev3_error",this.subtype=e}}var Xp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const em=[Kp.Alipay,Kp.IDEAL];class tm{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Xp(this,void 0,void 0,function*(){const{stripev3:t,methodId:n,gatewayId:i}=e;if(!i)throw new vi('Unable to initialize payment because "gatewayId" argument is not provided.');this.initializeOptions=t,this.isDeinitialize=!1;const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{initializationData:{stripePublishableKey:o,stripeConnectedAccount:a,useIndividualCardFields:s,allowRedisplayForStoredInstruments:d}}=r;this._allowRedisplayForStoredInstruments=d;const c=this.getInitializeOptions().form;this.useIndividualCardFields=s,this.stripeV3Client=yield this.loadStripeJs(o,a),this.isCreditCard(n)&&this.shouldShowTSVHostedForm(n,i)&&c?this.hostedForm=yield this.mountCardVerificationFields(c):this.stripeElement=yield this.mountCardFields(n)})}execute(e,t){var n,i;return Xp(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);let a,s;if(!r||!r.paymentData)throw new co(["payment.paymentData"]);const{paymentData:d,gatewayId:c,methodId:l}=r,{shouldSaveInstrument:u,shouldSetAsDefaultInstrument:h}=Bd(d)?d:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},p=H(em,l),{isStoreCreditApplied:m}=this.paymentIntegrationService.getState().getCheckoutOrThrow();m&&(yield this.paymentIntegrationService.applyStoreCredit(m));try{p&&(yield this.paymentIntegrationService.submitOrder(o,t)),c&&(yield this.paymentIntegrationService.loadPaymentMethod(c,{params:{method:l}}));const e=this.paymentIntegrationService.getState();if(Nd(d)){yield this.paymentIntegrationService.submitOrder(o,t);const{instrumentId:n}=d,i=e.getPaymentMethodOrThrow(r.methodId).clientToken;if(!i)throw new ni(ei.MissingPaymentMethod);return yield this.executeWithVaulted(r,n,h,i)}const m=e.getPaymentMethodOrThrow(l),y=yield this.confirmStripePayment(m),{clientToken:g,method:f}=m,{id:v}=null!==(i=null!==(n=y.paymentIntent)&&void 0!==n?n:y.paymentMethod)&&void 0!==i?i:{id:""};s=y.error,a={credit_card_token:{token:v},vault_payment_instrument:u,confirm:!1,set_as_default_stored_instrument:h},f===Kp.CreditCard&&(a.client_token=g),p||(yield this.paymentIntegrationService.submitOrder(o,t));const _=this.buildPaymentPayload(l,a,h);yield this.paymentIntegrationService.submitPayment(_)}catch(e){yield this.processAdditionalAction(this.handleEmptyPaymentIntentError(e,s),l,u,h)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this.hostedForm&&this.hostedForm.detach(),this.isDeinitialize=!0,this.unmountElement(),Promise.resolve()}buildPaymentPayload(e,t,n){return{methodId:e,paymentData:n?{formattedPayload:Object.assign(Object.assign({},t),{set_as_default_stored_instrument:n})}:{formattedPayload:t}}}isCancellationError(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))}isAuthError(e){return"payment_intent_authentication_failure"===(null==e?void 0:e.code)}isCreditCard(e){return e===Jp.CreditCard}isHostedFieldAvailable(){var e;const t=this.getInitializeOptions(),n=ue(null===(e=t.form)||void 0===e?void 0:e.fields,$);return!$(n)}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:n}=this.paymentIntegrationService.getState(),i=n(e,t);return Boolean(i.config.isHostedFormEnabled)}confirmStripePayment(e){return Xp(this,void 0,void 0,function*(){const{clientToken:t,method:n,returnUrl:i}=e;if(!t)throw new ni(ei.MissingPaymentMethod);switch(n){case Kp.Alipay:return this.getStripeJs().confirmAlipayPayment(t,{return_url:i},{handleActions:!1});case Kp.IDEAL:{const e=this.mapStripePaymentData(Jp.IDEAL,i);return this.getStripeJs().confirmIdealPayment(t,e,{handleActions:!1})}case Kp.Sepa:{const e=this.mapStripePaymentData(Jp.Sepa);return this.getStripeJs().confirmSepaDebitPayment(t,e)}default:{const e=this.useIndividualCardFields?this.getStripeCardElements()[0]:this.getStripeElement(),t=this.mapStripeBillingDetails(this.paymentIntegrationService.getState().getBillingAddress(),this.paymentIntegrationService.getState().getCustomer()),n=this._allowRedisplayForStoredInstruments;return this.getStripeJs().createPaymentMethod(Object.assign({type:Jp.CreditCard,card:e,billing_details:t},n?{allow_redisplay:"always"}:{}))}}})}executeWithVaulted(e,t,n,i){var r;return Xp(this,void 0,void 0,function*(){const o={bigpay_token:{token:t},confirm:!0,client_token:i,set_as_default_stored_instrument:n};if(this.isHostedPaymentFormEnabled(e.methodId,e.gatewayId)&&this.hostedForm){const t=this.hostedForm;return e.paymentData&&Nd(e.paymentData)&&(e.paymentData=Object.assign(Object.assign({},e.paymentData),{instrumentId:JSON.stringify({token:(null===(r=e.paymentData)||void 0===r?void 0:r.instrumentId)||"",client_token:i})})),yield t.validate(),yield t.submit(e),this.paymentIntegrationService.loadCurrentOrder()}const a=this.buildPaymentPayload(e.methodId,o,n);return this.paymentIntegrationService.submitPayment(a)})}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ti.PaymentNotInitialized);return this.initializeOptions}getStripeCardElements(){if(!this.stripeCardElements)throw new ri(ti.PaymentNotInitialized);return this.stripeCardElements}getStripeElement(){if(!this.stripeElement)throw new ri(ti.PaymentNotInitialized);return this.stripeElement}getStripeJs(){if(!this.stripeV3Client)throw new ri(ti.PaymentNotInitialized);return this.stripeV3Client}handleEmptyPaymentIntentError(e,t){return pa(e)&&fe(e.body.errors,{code:"required_field"})&&t?new Error(t.message):e}loadStripeJs(e,t){return Xp(this,void 0,void 0,function*(){return this.stripeV3Client?Promise.resolve(this.stripeV3Client):this.scriptLoader.load(e,t,this.paymentIntegrationService.getState().getLocale())})}mapStripeAddress(e){if(e){const{city:t,countryCode:n,address1:i,address2:r,postalCode:o,stateOrProvinceCode:a}=e;return{city:t,country:n,line1:i,line2:r,postal_code:o,state:a}}return{line1:""}}mapStripeBillingDetails(e,t){const{firstName:n,lastName:i}=e||t||{firstName:"Guest",lastName:""},r=`${n} ${i}`.trim(),{options:o}=this.getInitializeOptions();if(this.useIndividualCardFields&&$p(o)){const{zipCodeElementOptions:t}=o;if(t){const n=document.getElementById(t.containerId)?document.getElementById(t.containerId).value:"";n&&e&&(e=Object.assign(Object.assign({},e),{postalCode:n}))}}const a={address:this.mapStripeAddress(e)};if(t&&t.addresses[0]&&function(e){return"object"==typeof e&&null!==e&&"id"in e&&void 0!==e.id}(t.addresses[0])){const e=t.addresses[0],{email:n}=t,{phone:i}=e;return i?Object.assign(Object.assign({},a),{email:n,name:r,phone:i}):Object.assign(Object.assign({},a),{email:n,name:r})}if(e){const{email:t,phone:n}=e;return n?Object.assign(Object.assign({},a),{email:t,name:r,phone:n}):Object.assign(Object.assign({},a),{email:t,name:r})}return Object.assign(Object.assign({},a),{name:r})}mapStripePaymentData(e,t){const n=this.paymentIntegrationService.getState().getCustomer(),i=this.paymentIntegrationService.getState().getBillingAddress(),r={payment_method:{[e]:this.getStripeElement(),billing_details:this.mapStripeBillingDetails(i,n)}};return e===Jp.IDEAL?Object.assign(Object.assign({},r),{return_url:t}):r}mountCardFields(e){const{options:t,containerId:n}=this.getInitializeOptions();let i;return new Promise((r,o)=>{switch(this.stripeElements||(this.stripeElements=this.getStripeJs().elements()),e){case Kp.CreditCard:if(this.useIndividualCardFields&&$p(t)){const{cardNumberElementOptions:e,cardExpiryElementOptions:n,cardCvcElementOptions:r}=t,a=this.stripeElements.getElement(Kp.CardNumber)||this.stripeElements.create(Kp.CardNumber,e),s=this.stripeElements.getElement(Kp.CardExpiry)||this.stripeElements.create(Kp.CardExpiry,n),d=this.stripeElements.getElement(Kp.CardCvc)||this.stripeElements.create(Kp.CardCvc,r);this.stripeCardElements=[a,s,d],i=this.stripeCardElements[0];try{a.mount(`#${e.containerId}`),s.mount(`#${n.containerId}`),d.mount(`#${r.containerId}`)}catch(e){this.isDeinitialize||o(new vi("Unable to mount Stripe component without valid container ID."))}}else{i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new vi("Unable to mount Stripe component without valid container ID."))}}break;case Kp.IDEAL:case Kp.Sepa:i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new vi("Unable to mount Stripe component without valid container ID."))}case Kp.Alipay:}r(i)})}mountCardVerificationFields(e){return Xp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getStoreConfig();if(!t)throw new ni(ei.MissingCheckoutConfig);const n=t.paymentSettings.bigpayBaseUrl,i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}processAdditionalAction(e,t,n=!1,i=!1){return Xp(this,void 0,void 0,function*(){if(!pa(e))throw e;const r=fe(e.body.errors,{code:"additional_action_required"}),o=fe(e.body.errors,{code:"three_d_secure_required"});if(r){const t=e.body.additional_action_required;if(t&&"redirect_to_url"===t.type)return new Promise(()=>{t.data.redirect_url&&window.location.replace(t.data.redirect_url)})}if(o){const r=e.body.three_ds_result.token,o=!1;let a,s=!1;try{a=yield this.getStripeJs().confirmCardPayment(r)}catch(e){s=!0}if(null==a?void 0:a.error){if(this.isCancellationError(a.error))throw new Wi;if(this.isAuthError(a.error))throw new Qp(Zp.AuthFailure);throw new Error(a.error.message)}const d={credit_card_token:{token:this.getPaymentToken(null==a?void 0:a.paymentIntent,r,s)},vault_payment_instrument:n,confirm:o},c=this.buildPaymentPayload(t,d,i);try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){throw this.handleEmptyPaymentIntentError(e,null==a?void 0:a.error)}}throw e})}getPaymentToken(e,t,n){return!e||n?t:e.id}shouldShowTSVHostedForm(e,t){return this.isHostedFieldAvailable()&&this.isHostedPaymentFormEnabled(e,t)}unmountElement(){this.stripeElement&&(this.stripeElement.unmount(),this.stripeElement=void 0)}}class nm{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}load(e,t,n){return this.scriptLoader.loadScript("https://js.stripe.com/v3/").then(()=>{if(!this.stripeWindow.Stripe)throw new mi;return this.stripeWindow.Stripe(e,{stripeAccount:t,locale:n,betas:["payment_intent_beta_3","alipay_pm_beta_1"],apiVersion:"2020-03-02;alipay_beta=v1"})})}}const im=fi(e=>new tm(e,new nm(a())),[{gateway:"stripev3"}]),rm={ar:["ar"],bg:["bg"],cs:["cs"],da:["da"],de:["de"],el:["el"],en:["en","en-GB"],es:["es","es-419"],et:["et"],fi:["fi"],fil:["fil"],fr:["fr","fr-CA"],he:["he"],hr:["hr"],hu:["hu"],id:["id"],it:["it"],ja:["ja"],ko:["ko"],lt:["lt"],lv:["lv"],ms:["ms"],mt:["mt"],nb:["nb"],nl:["nl"],pl:["pl"],pt:["pt","pt-BR"],ro:["ro"],ru:["ru"],sk:["sk"],sl:["sl"],sv:["sv"],th:["th"],tr:["tr"],vi:["vi"],zh:["zh","zh-HK","zh-TW"]};function om(e){const[t,n]=e.replace(/_/g,"-").toLowerCase().split("-"),i=rm[t];if(!i)return"auto";const r=n?`${t}-${n.toUpperCase()}`:t;return i.indexOf(r)>-1?r:i[0]}var am=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class sm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){return am(this,void 0,void 0,function*(){const{stripeupe:t,methodId:n,gatewayId:i}=e;if(!(null==t?void 0:t.containerId))throw new ri(ti.PaymentNotInitialized);if(!i)throw new vi('Unable to initialize payment because "gatewayId" argument is not provided.');return this._loadStripeElement(t,i,n).catch(e=>{var n;return null===(n=t.onError)||void 0===n?void 0:n.call(t,e)}),this.stripeIntegrationService.initCheckoutEventsSubscription(i,n,t,this._stripeElements),Promise.resolve()})}execute(e,t){return am(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n||!n.paymentData)throw new co(["payment.paymentData"]);if(!this._stripeUPEClient)throw new ri(ti.PaymentNotInitialized);const{paymentData:r,methodId:o,gatewayId:a}=n,{shouldSaveInstrument:s=!1,shouldSetAsDefaultInstrument:d=!1}=Bd(r)?r:{},c=this.paymentIntegrationService.getState(),{isStoreCreditApplied:l}=c.getCheckoutOrThrow(),u=c.getPaymentProviderCustomerOrThrow(),h=(cd(u)?u:{}).stripeLinkAuthenticationState;if(l&&(yield this.paymentIntegrationService.applyStoreCredit(l)),a){yield this.stripeIntegrationService.updateStripePaymentIntent(a,o);const{email:e}=c.getCustomerOrThrow();if(void 0!==h&&!e){const e=c.getBillingAddressOrThrow();yield this.paymentIntegrationService.updateBillingAddress(e)}}if(yield this.paymentIntegrationService.submitOrder(i,t),Nd(r)){const{instrumentId:e}=r;return void(yield this._executeWithVaulted(n.methodId,e,d))}yield this._executeWithStripeConfirmation(n.methodId,n.gatewayId,!h&&s,d)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Da.PAYMENT))||void 0===t||t.unmount(),this.stripeIntegrationService.deinitialize(),this._stripeElements=void 0,this._stripeUPEClient=void 0,Promise.resolve()}_executeWithStripeConfirmation(e,t,n,i){return am(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),{clientToken:o}=r.getPaymentMethodOrThrow(e),a=this._getPaymentPayload(e,o||"",n,i);try{yield this.paymentIntegrationService.submitPayment(a)}catch(r){yield this._processAdditionalActionWithStripeConfirmation(r,e,t,n,i)}})}_executeWithVaulted(e,t,n){var i;return am(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(e),a=null===(i=r.getCart())||void 0===i?void 0:i.id;try{const i={methodId:e,paymentData:{formattedPayload:{cart_id:a,bigpay_token:{token:t},confirm:!1,client_token:o.clientToken,set_as_default_stored_instrument:n}}};return yield this.paymentIntegrationService.submitPayment(i)}catch(t){return this._processVaultedAdditionalAction(t,e,n)}})}_loadStripeElement(e,t,n){return am(this,void 0,void 0,function*(){const{containerId:i,style:r,render:o,initStripeElementUpdateTrigger:a}=e,s=yield this.paymentIntegrationService.loadPaymentMethod(t,{params:{method:n}}),d=s.getPaymentMethodOrThrow(n);if(!dd(d))throw new ni(ei.MissingPaymentMethod);const{clientToken:c,initializationData:l}=d,{shopperLanguage:u,allowRedisplayForStoredInstruments:h=!1,enableLink:p}=l;if(this._allowRedisplayForStoredInstruments=h,!c)throw new ni(ei.MissingPaymentMethod);let m;if(this._stripeUPEClient=yield this._loadStripeJs(l),this._isStripeElementUpdateEnabled="function"==typeof a,r){const e=r;m={variables:this.stripeIntegrationService.mapAppearanceVariables(r),rules:{".Input":this.stripeIntegrationService.mapInputAppearanceRules(e)}}}this._stripeElements=yield this.scriptLoader.getElements(this._stripeUPEClient,{clientSecret:c,locale:om(u),appearance:m});const{getBillingAddress:y,getShippingAddress:g}=s,{postalCode:f}=g()||y()||{},v=this._stripeElements.getElement(Da.PAYMENT)||this._stripeElements.create(Da.PAYMENT,Object.assign({fields:{billingDetails:{email:Ta.NEVER,address:{country:Ta.NEVER,city:Ta.NEVER,postalCode:f?Ta.NEVER:Ta.AUTO}}},wallets:{applePay:Ta.NEVER,googlePay:Ta.NEVER,link:p?Ta.AUTO:Ta.NEVER}},this._getStripeElementTerms()));this.stripeIntegrationService.mountElement(v,i),v.on(za.READY,()=>{o()}),v.on(za.CHANGE,e=>{(null==e?void 0:e.value)&&"type"in e.value&&this._updateStripeLinkStateByElementType(e.value.type)}),this._isStripeElementUpdateEnabled&&(null==a||a(this._updateStripeElement.bind(this)))})}_processAdditionalActionWithStripeConfirmation(e,t,n,i=!1,r=!1){return am(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ti.PaymentNotInitialized);const{data:o}=e.body.additional_action_required,{token:a}=o,{paymentIntent:s,error:d}=yield this._confirmStripePaymentOrThrow(t,o),c=this._getPaymentPayload(t,(null==s?void 0:s.id)||a,i,r);if(d||!s){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(d)}try{yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return am(this,void 0,void 0,function*(){if(!this._stripeUPEClient)throw new ri(ti.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,i,!!this._allowRedisplayForStoredInstruments);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this._stripeUPEClient))?this._stripeUPEClient.retrievePaymentIntent(n||""):this._stripeUPEClient.confirmPayment(r)})}_processVaultedAdditionalAction(e,t,n=!1){var i;return am(this,void 0,void 0,function*(){if(!t||!pa(e)||!fe(e.body.errors,{code:"three_d_secure_required"}))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ti.PaymentNotInitialized);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this._stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this._stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if((null==o?void 0:o.error)&&this.stripeIntegrationService.throwStripeError(o.error),!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;const s=this._getPaymentPayload(t,a?r:null===(i=null==o?void 0:o.paymentIntent)||void 0===i?void 0:i.id,!1,n);return this.paymentIntegrationService.submitPayment(s)})}_loadStripeJs(e){return am(this,void 0,void 0,function*(){if(this._stripeUPEClient)return this._stripeUPEClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.V3,Fa,La)})}_getPaymentPayload(e,t,n=!1,i=!1){var r;return{methodId:e,paymentData:{formattedPayload:{cart_id:(null===(r=this.paymentIntegrationService.getState().getCart())||void 0===r?void 0:r.id)||"",credit_card_token:{token:t},confirm:!1,vault_payment_instrument:n,set_as_default_stored_instrument:i}}}}_updateStripeElement({shouldShowTerms:e}){var t;const n=null===(t=this._stripeElements)||void 0===t?void 0:t.getElement(Da.PAYMENT);null==n||n.update(Object.assign({},this._getStripeElementTerms(e)))}_getStripeElementTerms(e){let t=Ta.AUTO;return this._isStripeElementUpdateEnabled&&(t=e?Ta.AUTO:Ta.NEVER),{terms:{card:t}}}_updateStripeLinkStateByElementType(e){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),n=e===Aa.Link;!cd(t)&&n&&this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:n})}}const dm=fi(e=>{const t=new Ra(a());return new sm(e,t,new pd(e,t))},[{gateway:"stripeupe"},{gateway:"stripeupe",id:"klarna"}]),cm=e=>"object"==typeof e&&null!==e&&"value"in e&&"collapsed"in e;var lm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class um{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return lm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId))throw new ri(ti.PaymentNotInitialized);if(!r)throw new vi('Unable to initialize payment because "gatewayId" argument is not provided.');try{yield this._initializeStripeElement(n,r,i)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}this.stripeIntegrationService.initCheckoutEventsSubscription(r,i,n,this.stripeElements)})}execute(e,t){return lm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{methodId:r,gatewayId:o}=n||{};if(!this.stripeClient)throw new ri(ti.PaymentNotInitialized);if(!o||!r)throw new vi('Unable to initialize payment because "gatewayId" or "methodId" argument is not provided.');const{isStoreCreditApplied:a}=this.paymentIntegrationService.getState().getCheckoutOrThrow();a&&(yield this.paymentIntegrationService.applyStoreCredit(a)),yield this.stripeIntegrationService.updateStripePaymentIntent(o,r),yield this.paymentIntegrationService.submitOrder(i,t);const{clientToken:s}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(r,o),d=this._getPaymentPayload(r,s||"");try{yield this.paymentIntegrationService.submitPayment(d)}catch(e){yield this._processAdditionalAction(e,r,o)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Da.PAYMENT);return null==t||t.unmount(),null==t||t.destroy(),this.stripeIntegrationService.deinitialize(),this.stripeElements=void 0,this.stripeClient=void 0,Promise.resolve()}_initializeStripeElement(e,t,n){return lm(this,void 0,void 0,function*(){let i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t);if((null==i?void 0:i.clientToken)||(i=(yield this.paymentIntegrationService.loadPaymentMethod(t,{params:{method:n}})).getPaymentMethodOrThrow(n,t)),!dd(i))throw new ni(ei.MissingPaymentMethod);const{clientToken:r,initializationData:o}=i,{customerSessionToken:a,enableLink:s}=o;if(!r)throw new ni(ei.MissingPaymentMethod);this.stripeClient=yield this._loadStripeJs(o);const{appearance:d,containerId:c,fonts:l,layout:u,render:h,paymentMethodSelect:p,handleClosePaymentMethod:m,togglePreloader:y}=e;this.stripeElements=yield this.scriptLoader.getElements(this.stripeClient,{clientSecret:r,customerSessionClientSecret:a,appearance:d,fonts:l});const{getBillingAddress:g,getShippingAddress:f}=this.paymentIntegrationService.getState(),v=g(),{postalCode:_}=f()||v||{},S=this.stripeElements.getElement(Da.PAYMENT)||this.stripeElements.create(Da.PAYMENT,{fields:{billingDetails:{email:Ta.NEVER,address:{country:Ta.NEVER,city:Ta.NEVER,postalCode:_?Ta.NEVER:Ta.AUTO}}},wallets:{applePay:Ta.NEVER,googlePay:Ta.NEVER,link:s?Ta.AUTO:Ta.NEVER},layout:u,savePaymentMethod:{maxVisiblePaymentMethods:20},defaultValues:{billingDetails:{email:(null==v?void 0:v.email)||""}}});this.stripeIntegrationService.mountElement(S,c),S.on(za.LOADER_START,()=>{null==y||y(!1)}),S.on(za.READY,()=>{h()}),S.on(za.CHANGE,e=>{this._onStripeElementChange(e,t,n,p)}),null==m||m(this._collapseStripeElement.bind(this))})}_loadStripeJs(e){return lm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState(),n=this.stripeIntegrationService.getStripeJsVersion(e);return this.scriptLoader.getStripeClient(e,t.getCartLocale(),n)})}_collapseStripeElement(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Da.PAYMENT);null==t||t.collapse()}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",{card:o,us_bank_account:a}=n||{},s=this._shouldSaveInstrument(o)||this._shouldSaveInstrument(a),d=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:s},d)}}}_processAdditionalAction(e,t,n){return lm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this.stripeClient||!this.stripeElements)throw new ri(ti.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:r}=i,{paymentIntent:o,error:a}=yield this._confirmStripePaymentOrThrow(t,i),{client_secret:s,payment_method_options:d}=o||{},c=this._getPaymentPayload(t,s||r,d);if(a||!o){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(a)}try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return lm(this,void 0,void 0,function*(){if(!this.stripeClient)throw new ri(ti.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this.stripeElements,i);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this.stripeClient))?this.stripeClient.retrievePaymentIntent(n||""):this.stripeClient.confirmPayment(r)})}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_shouldSaveInstrument(e){const t=null==e?void 0:e.setup_future_usage;return t===xa.ON_SESSION||t===xa.OFF_SESSION}_getTokenizedOptions(e,t){return this._shouldSaveInstrument(null==t?void 0:t.us_bank_account)?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}}const hm=fi(e=>{const t=new Ra(a());return new um(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"optimized_checkout"}]);var pm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class mm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return pm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId)||!r)throw new ri(ti.PaymentNotInitialized);let o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r);(null==o?void 0:o.clientToken)||(yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:i}}),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r));try{yield this._initStripeCheckoutSession(n,o),yield this._updateStripeShopperData(),this._initializePaymentElement(n,o),this._initializeAdaptivePricingElement(n,o)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}})}execute(e,t){return pm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{methodId:r,gatewayId:o}=n||{};if(!this.stripeClient)throw new ri(ti.PaymentNotInitialized);if(!o||!r)throw new vi('Unable to initialize payment because "gatewayId" or "methodId" argument is not provided.');const a=this.paymentIntegrationService.getState(),{isStoreCreditApplied:s}=a.getCheckoutOrThrow();s&&(yield this.paymentIntegrationService.applyStoreCredit(s)),yield this._updateCheckoutSessionData(o,r),yield this.paymentIntegrationService.submitOrder(i,t);const{clientToken:d}=a.getPaymentMethodOrThrow(r,o),c=this._getPaymentPayload(r,d||"");try{yield this.paymentIntegrationService.submitPayment(c)}catch(e){yield this._processAdditionalAction(e,o,r)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e,t;const n=null===(e=this.stripeCheckout)||void 0===e?void 0:e.getPaymentElement(),i=null===(t=this.stripeCheckout)||void 0===t?void 0:t.getCurrencySelectorElement();return null==n||n.unmount(),null==n||n.destroy(),null==i||i.unmount(),null==i||i.destroy(),this.stripeCheckout=void 0,this.stripeClient=void 0,this.selectedMethodId=void 0,Promise.resolve()}_initStripeCheckoutSession(e,t){return pm(this,void 0,void 0,function*(){const{clientToken:n,initializationData:i}=t;if(!n||!i)throw new ni(ei.MissingPaymentMethod);this.stripeClient=yield this._loadStripeJs(i);const{appearance:r,fonts:o}=e;this.stripeCheckout=yield this.scriptLoader.getStripeCheckout(this.stripeClient,{clientSecret:n,elementsOptions:{appearance:r,fonts:o},adaptivePricing:{allowed:!!(null==i?void 0:i.adaptivePricingEnabled)}})})}_initializePaymentElement(e,t){const{initializationData:n,id:i,gateway:r}=t,{enableLink:o}=n||{},{containerId:a,layout:s,render:d,paymentMethodSelect:c,handleClosePaymentMethod:l,togglePreloader:u}=e,h=this._getStripeElement({fields:{billingDetails:{email:Ta.NEVER,name:Ta.NEVER,address:Ta.NEVER}},wallets:{applePay:Ta.NEVER,googlePay:Ta.NEVER,link:o?Ta.AUTO:Ta.NEVER},layout:s});if(!h||!r)throw new ri(ti.PaymentNotInitialized);this.stripeIntegrationService.mountElement(h,a),h.on(za.LOADER_START,()=>{null==u||u(!1)}),h.on(za.READY,()=>{d()}),h.on(za.CHANGE,e=>{this._onStripeElementChange(e,r,i,c)}),null==l||l(this._collapseStripeElement.bind(this))}_loadStripeJs(e){return pm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.CLOVER)})}_getStripeActionsOrThrow(){return pm(this,void 0,void 0,function*(){if(!this.stripeCheckout)throw new ri(ti.PaymentNotInitialized);const{actions:e,error:t}=yield this.stripeCheckout.loadActions();if(!e||t)throw new Qr(null==t?void 0:t.message);return e})}_getStripeElement(e){var t,n;return(null===(t=this.stripeCheckout)||void 0===t?void 0:t.getPaymentElement())||(null===(n=this.stripeCheckout)||void 0===n?void 0:n.createPaymentElement(e))}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_collapseStripeElement(){var e;const t=null===(e=this.stripeCheckout)||void 0===e?void 0:e.getPaymentElement();null==t||t.collapse()}_updateCheckoutSessionData(e,t){return pm(this,void 0,void 0,function*(){yield this._updateStripeShopperData(),yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}})})}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",o=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:!!n},o)}}}_processAdditionalAction(e,t,n){var i;return pm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;const{data:r}=(null===(i=e.body)||void 0===i?void 0:i.additional_action_required)||{},{token:o}=r||{},a=yield this._getStripeSavedPaymentMethodsOrThrow(),{session:s,error:d}=yield this._confirmStripePayment(r),c=yield this._getStripeSavedPaymentMethodsOrThrow(s),{id:l,status:u}=s||{},h=this._getNewVaultedStripeInstrument(a,c),p=this._getPaymentPayload(n,l||o,h),{initializationData:m}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{sendSecondPaymentRequestOnStripeError:y}=m||{};if(d||!s){if(y)try{const e=de({},p,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}throw new Qr(null==d?void 0:d.message)}try{return yield this.paymentIntegrationService.submitPayment(p)}catch(e){throw(null==u?void 0:u.paymentStatus)===Oa.Paid&&this.stripeIntegrationService.throwPaymentConfirmationProceedMessage(),e}})}_confirmStripePayment(e){return pm(this,void 0,void 0,function*(){const{redirect_url:t}=e||{};if(!this.stripeCheckout)throw new ri(ti.PaymentNotInitialized);return(yield this._getStripeActionsOrThrow()).confirm({redirect:Ta.IF_REQUIRED,returnUrl:t})})}_updateStripeShopperData(){return pm(this,void 0,void 0,function*(){const e=yield this._getStripeActionsOrThrow();yield this._updateStripeEmail(e),yield this._updateStripeShippingAddress(e),yield this._updateStripeBillingAddress(e)})}_updateStripeEmail(e){return pm(this,void 0,void 0,function*(){if((yield e.getSession()).email)return;const{getBillingAddress:t}=this.paymentIntegrationService.getState(),n=t();yield e.updateEmail((null==n?void 0:n.email)||"")})}_updateStripeShippingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getShippingAddress();t&&(yield e.updateShippingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_updateStripeBillingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getBillingAddress();t&&(yield e.updateBillingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_getStripeSavedPaymentMethodsOrThrow(e){return pm(this,void 0,void 0,function*(){if(null==e?void 0:e.savedPaymentMethods)return e.savedPaymentMethods;const t=yield this._getStripeActionsOrThrow(),{savedPaymentMethods:n}=yield t.getSession();return n||[]})}_getNewVaultedStripeInstrument(e,t){return t.find(t=>!e.some(e=>e.id===t.id))}_getTokenizedOptions(e,t){return(null==t?void 0:t.type)===Aa.ACH?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}_initializeAdaptivePricingElement(e,t){const{initializationData:n}=t,{currencySelectorContainerId:i}=e;if(!(null==n?void 0:n.adaptivePricingEnabled))return;if(!i)throw new ri(ti.PaymentNotInitialized);const r=this._getCurrencySelectorElement();r&&(r.mount(`#${i}`),this._initAdaptivePricingEvents(r))}_getCurrencySelectorElement(){var e,t;return(null===(e=this.stripeCheckout)||void 0===e?void 0:e.getCurrencySelectorElement())||(null===(t=this.stripeCheckout)||void 0===t?void 0:t.createCurrencySelectorElement())}_initAdaptivePricingEvents(e){e.on(za.CHANGE,e=>pm(this,void 0,void 0,function*(){if(!e.value||!("currency"in e.value))return;const{currency:t}=this.paymentIntegrationService.getState().getCartOrThrow(),n=t.code.toLowerCase(),i=e.value.currency.toLowerCase();yield this.paymentIntegrationService.updatePaymentProviderCustomer({isCustomerCurrencySelected:n!==i,customerCurrency:i})}))}}const ym=fi(e=>{const t=new Ra(a());return new mm(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"checkout_session"}]);var gm;!function(e){e.CARD_NUMBER="card-number",e.CVV="cvv",e.EXPIRY="expiry"}(gm||(gm={}));var fm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vm{constructor(e,t,n){this.paymentIntegrationService=e,this.tdOnlineMartScriptLoader=t,this.formPoster=n,this.tdInputs=[{id:"ccNumber",fieldType:gm.CARD_NUMBER},{id:"ccCvv",fieldType:gm.CVV},{id:"ccExpiry",fieldType:gm.EXPIRY}]}initialize(e){return fm(this,void 0,void 0,function*(){const{methodId:t}=e;if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');this.tdOnlineMartClient=yield this.loadTDOnlineMartJs(),this.mountHostedFields(t)})}execute(e,t){return fm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);if(!n.methodId)throw new ni(ei.MissingPaymentMethod);const r=yield this.getPaymentPayloadOrThrow(n);yield this.paymentIntegrationService.submitOrder(i,t);try{yield this.paymentIntegrationService.submitPayment(r)}catch(e){yield this.processWithAdditionalAction(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this.tdOnlineMartClient=void 0,this.tdInputs.forEach(({inputElement:e})=>{null==e||e.unmount()}),Promise.resolve()}getPaymentPayloadOrThrow(e){return fm(this,void 0,void 0,function*(){const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=Bd(n)?n:{},o={browser_info:ss(),shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r};if(Bd(n)&&Nd(n)&&n.instrumentId){const e=!!this.paymentIntegrationService.getState().getCartOrThrow().lineItems.digitalItems.length,i=!this.isTrustedVaultingInstrument(n.instrumentId)||e;return{methodId:t,paymentData:Object.assign(Object.assign(Object.assign({},o),{instrumentId:n.instrumentId}),i?{nonce:n.instrumentId}:{})}}let a;try{a=yield this.getTokenOrThrow()}catch(e){this.throwTokenizationError(e)}return{methodId:t,paymentData:Object.assign(Object.assign({},o),{nonce:a})}})}mountHostedFields(e){const t=this.getHostedFieldsOptions(),n=this.getTDOnlineMartClientOrThrow();this.tdInputs.forEach(i=>{const r=`${e}-${i.id}`;document.getElementById(r)&&(i.inputElement=n.create(i.fieldType,t),i.inputElement.mount(`#${r}`))})}loadTDOnlineMartJs(){return fm(this,void 0,void 0,function*(){return this.tdOnlineMartClient?this.tdOnlineMartClient:this.tdOnlineMartScriptLoader.load()})}getTokenOrThrow(){return new Promise((e,t)=>{this.getTDOnlineMartClientOrThrow().createToken(n=>{const{error:i,token:r}=n;if(i||!r)return t(i);e(r)})})}getTDOnlineMartClientOrThrow(){if(!this.tdOnlineMartClient)throw new ri(ti.PaymentNotInitialized);return this.tdOnlineMartClient}processWithAdditionalAction(e){return fm(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&fe(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}throwTokenizationError(e){if(!function(e){return"object"==typeof e&&null!==e&&"field"in e&&"type"in e&&"message"in e}(e))throw new ni(ei.MissingPaymentToken);throw new Error(e.message)}getHostedFieldsOptions(){return{style:{error:{color:"#d14343"}},classes:{error:"form-input--error"}}}isTrustedVaultingInstrument(e){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e);return!(uc(n)&&!n.trustedShippingAddress)}}class _m{constructor(e,t=window){this.scriptLoader=e,this.tdOnlineMartWindow=t}load(){return e=this,t=void 0,i=function*(){if(this.tdOnlineMartWindow.customcheckout||(yield this.scriptLoader.loadScript("https://libs.na.bambora.com/customcheckout/1/customcheckout.js")),!this.tdOnlineMartWindow.customcheckout)throw new mi;return this.tdOnlineMartWindow.customcheckout()},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const Sm=fi(e=>new vm(e,new _m(a()),Ee()),[{id:"tdonlinemart"}]);var Im=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const wm="Payment cannot continue";let Cm;class bm extends tu{initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Im(this,void 0,void 0,function*(){if(this._initializeOptions=e&&e.worldpay,!this._initializeOptions)throw new ri(ti.PaymentNotInitialized);return t.initialize.call(this,e)})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Im(this,void 0,void 0,function*(){const{payment:i}=e;if(Cm=this._submitAdditionalAction(),!i)throw new co(["payment"]);try{return yield n.execute.call(this,e,t)}catch(e){return this._processAdditionalAction(e,i)}})}_processAdditionalAction(e,t){return Im(this,void 0,void 0,function*(){return pa(e)&&fe(e.body.errors,{code:"additional_action_required"})?new Promise((n,i)=>{const r=e=>Im(this,void 0,void 0,function*(){if(-1===e.origin.indexOf("cardinalcommerce.com"))return;if("string"!=typeof e.data||!this._isValidJsonWithSessionId(e.data))return i(new Error(wm));window.removeEventListener("message",r),o.remove();const a=JSON.parse(e.data),s=de({},t,{paymentData:{threeDSecure:{token:a.SessionId}}});try{n(yield Cm(s))}catch(e){if(!pa(e)||!fe(e.body.errors,{code:"three_d_secure_required"}))return i(e);if(!this._initializeOptions)return i(new ri(ti.PaymentNotInitialized));const{onLoad:t}=this._initializeOptions,n=this._createIframe(e.body.three_ds_result);try{t(n,()=>i(new Error("Payment was cancelled")))}catch(e){i(new Error(wm))}}});let o;window.addEventListener("message",r);try{o=this._createHiddenIframe(e.body)}catch(e){throw window.removeEventListener("message",r),new Error(wm)}}):Promise.reject(e)})}_createHiddenIframe(e){const t=document.createElement("iframe");if(document.body.appendChild(t),!t.contentWindow)throw new Error;t.id="worldpay_hosted_hidden_payment_page",t.height="0px",t.width="0px";const n=document.createElement("form"),i="collectionForm";n.id=i,n.name="devicedata",n.method="post";const r=e.additional_action_required.data.redirect_url;n.action=r;const o=document.createElement("input");o.name="Bin",o.type="hidden",o.value=e.provider_data.source_id,n.appendChild(o);const a=document.createElement("input");a.name="JWT",a.type="hidden",a.value=e.provider_data.data,n.appendChild(a);const s=document.createElement("button");s.type="submit",s.id="btnsubmit",n.appendChild(s),navigator.userAgent.match("Firefox")?t.srcdoc=n.outerHTML:t.contentWindow.document.body.appendChild(n);const d=document.createElement("script");return d.innerHTML=`\n document.getElementById('${i}').submit();\n `,t.contentWindow.document.body.appendChild(d),t}_createIframe(e){const t=document.createElement("form");t.id="challengeForm",t.method="POST",t.action=e.acs_url;const n=document.createElement("input");n.name="JWT",n.type="hidden",n.value=e.payer_auth_request,t.appendChild(n);const i=document.createElement("input");i.name="MD",i.type="hidden",i.value=`merchantSessionId=${e.merchant_data}`,t.appendChild(i);const r=document.createElement("script");r.type="text/javascript",r.innerHTML="window.onload = function() { document.getElementById('challengeForm').submit(); }";const o=document.createElement("iframe");return o.name="worldpay_hosted_payment_page",o.height="400",o.width="100%",o.srcdoc=`${t.outerHTML} ${r.outerHTML}`,o}_submitAdditionalAction(){if(this._shouldRenderHostedForm){if(!this._hostedForm)throw new ri(ti.PaymentNotInitialized);const e=this._hostedForm;return t=>Im(this,void 0,void 0,function*(){yield e.submit(t)})}return e=>Im(this,void 0,void 0,function*(){yield this._paymentIntegrationService.submitPayment(e)})}_isValidJsonWithSessionId(e){try{const t=JSON.parse(e);return!(!t.SessionId||!t.Status)}catch(e){return!1}}}const Pm=fi(e=>new bm(e),[{gateway:"worldpayaccess",id:"credit_card"},{id:"worldpayaccess"}]);class Om{constructor(e){this._paymentIntegrationService=e}execute({payment:e}){return t=this,n=void 0,r=function*(){if(!e)throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(e)}catch(e){if(this._isWorldpayAccessRedirectResponse(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_isWorldpayAccessRedirectResponse(e){var t,n;if("object"!=typeof e||null===e)return!1;const i=e;if(!i.body)return!1;const r=i.body;return"additional_action_required"===r.status&&!!(null===(n=null===(t=r.additional_action_required)||void 0===t?void 0:t.data)||void 0===n?void 0:n.redirect_url)}}const Em=fi(e=>new Om(e),[{id:"open_banking",gateway:"worldpayaccess"}]);class Am{constructor(e){this._requestSender=e}saveExternalId(e,t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/payment/${e}/save-external-id`,i={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{externalId:t,provider:e}};yield this._requestSender.post(n,i)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}class Tm{constructor(e,t){this.paymentIntegrationService=e,this.storefrontPaymentRequestSender=t}initialize(){return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{methodId:r}=n,{getPaymentMethodOrThrow:o}=yield this.paymentIntegrationService.loadPaymentMethod(r,t),{clientToken:a,initializationData:s}=o(r),d=null==s?void 0:s.redirectUrl;if(!a||!d)throw new ni(ei.MissingPaymentMethod);const{id:c}=JSON.parse(a);if(!c)throw new ni(ei.MissingPaymentToken);const{isStoreCreditApplied:l}=this.paymentIntegrationService.getState().getCheckoutOrThrow();yield this.paymentIntegrationService.applyStoreCredit(l),yield this.paymentIntegrationService.initializePayment(r,{useStoreCredit:l}),yield this.paymentIntegrationService.submitOrder(i,t),yield this._prepareForReferredRegistration(r,c);try{yield this.paymentIntegrationService.submitPayment({methodId:r,paymentData:{nonce:c}})}catch(e){if(pa(e)&&"additional_action_required"===e.body.status)return new Promise(()=>window.location.replace(d));throw e}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_prepareForReferredRegistration(e,t){return this.storefrontPaymentRequestSender.saveExternalId(e,t)}}const km=fi(e=>{const{getHost:t}=e.getState(),i=n({host:t()}),r=new Am(i);return new Tm(e,r)},[{id:"zip"},{id:"quadpay"}]);var Dm,Mm;!function(e){e.LoadCountriesRequested="LOAD_COUNTRIES_REQUESTED",e.LoadCountriesSucceeded="LOAD_COUNTRIES_SUCCEEDED",e.LoadCountriesFailed="LOAD_COUNTRIES_FAILED"}(Dm||(Dm={}));class zm{constructor(e){this._countryRequestSender=e}loadCountries(e){return m.create(t=>{t.next(l(Dm.LoadCountriesRequested)),this._countryRequestSender.loadCountries(e).then(e=>{t.next(l(Dm.LoadCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Dm.LoadCountriesFailed,e))})})}}class xm{constructor(e,t){this._requestSender=e,this._config=t}loadCountries({timeout:e}={}){const t=Object.assign({"Accept-Language":this._config.locale},et);return this._requestSender.get("/internalapi/v1/store/countries",{headers:t,timeout:e})}}class Nm extends rt{constructor(e){super(e||"Your checkout could not be processed because some details have changed. Please review your order and try again."),this.name="CartConsistencyError",this.type="cart_consistency"}}class Rm extends rt{constructor(e,t){super(t||"At least one item changed stock position. Please review your cart and try again."),this.name="CartStockPositionsChangedError",this.type="cart_stock_positions_changed",this.changedItemIds=e}}class Fm extends rt{constructor(e){super(e||"The tax provider is unavailable."),this.name="OrderTaxProviderUnavailableError",this.type="tax_provider_unavailable"}}class Lm extends rt{constructor(e){super(e),this.name="MissingShippingMethodError",this.type="missing_shipping_method"}}class jm extends rt{constructor(e){super(e),this.name="InvalidShippingAddressError",this.type="invalid_shipping_address"}}class Bm{constructor(e){this._requestSender=e}loadOrder(e,{timeout:t}={}){const n=`/api/storefront/orders/${e}`,i=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.get(n,{params:{include:Lt(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:t})}submitOrder(e,{headers:t,timeout:n}={}){return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:ue(Object.assign({"X-Checkout-Variant":t&&t.checkoutVariant},et),J),timeout:n}).catch(e=>{var t,n;if("tax_provider_unavailable"===e.body.type)throw new Fm;if("cart_has_changed"===e.body.type)throw new Nm;if("cart_stock_positions_changed"===e.body.type){const i=null!==(n=null===(t=e.body.errors)||void 0===t?void 0:t.changedItemIds)&&void 0!==n?n:[];throw new Rm(i)}if("missing_shipping_method"===e.body.type)throw new Lm(e.body.detail);if("invalid_shipping_address"===e.body.type)throw new jm(e.body.detail);if("empty_cart"===e.body.type)throw new ct;throw e})}finalizeOrder(e,{timeout:t}={}){const n=`/internalapi/v1/checkout/order/${e}`;return this._requestSender.post(n,{timeout:t,headers:et})}}class Um extends rt{constructor(){super("You haven't complete our spam check. Please try again."),this.name="SpamProtectionNotCompletedError",this.type="spam_protection_not_completed"}}!function(e){e.LoadOrderRequested="LOAD_ORDER_REQUESTED",e.LoadOrderSucceeded="LOAD_ORDER_SUCCEEDED",e.LoadOrderFailed="LOAD_ORDER_FAILED",e.LoadOrderPaymentsRequested="LOAD_ORDER_PAYMENTS_REQUESTED",e.LoadOrderPaymentsSucceeded="LOAD_ORDER_PAYMENTS_SUCCEEDED",e.LoadOrderPaymentsFailed="LOAD_ORDER_PAYMENTS_FAILED",e.SubmitOrderRequested="SUBMIT_ORDER_REQUESTED",e.SubmitOrderSucceeded="SUBMIT_ORDER_SUCCEEDED",e.SubmitOrderFailed="SUBMIT_ORDER_FAILED",e.FinalizeOrderRequested="FINALIZE_ORDER_REQUESTED",e.FinalizeOrderSucceeded="FINALIZE_ORDER_SUCCEEDED",e.FinalizeOrderFailed="FINALIZE_ORDER_FAILED"}(Mm||(Mm={}));var qm;class Vm{constructor(e,t){this._orderRequestSender=e,this._checkoutValidator=t}loadOrder(e,t){return new m(n=>{n.next(l(Mm.LoadOrderRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderFailed,e))})})}loadOrderPayments(e,t){return new m(n=>{n.next(l(Mm.LoadOrderPaymentsRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderPaymentsSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderPaymentsFailed,e))})})}loadCurrentOrder(e){return t=>f(()=>{const n=this._getCurrentOrderId(t.getState());if(!n)throw new ot(tt.MissingOrderId);return this.loadOrder(n,e)})}submitOrder(e,t){return n=>g(C(l(Mm.SubmitOrderRequested)),f(()=>{const i=n.getState(),r=i.config.getExternalSource(),o=i.config.getVariantIdentificationToken(),a=i.checkout.getCheckout();if(!a)throw new ot(tt.MissingCheckout);if(a.shouldExecuteSpamCheck)throw new Um;return _(this._checkoutValidator.validate(a,t).then(()=>this._orderRequestSender.submitOrder(this._mapToOrderRequestBody(null!=e?e:{},a.id,a.customerMessage,r),Object.assign(Object.assign({},t),{headers:{checkoutVariant:o}})))).pipe(M(e=>g(this.loadOrder(e.body.data.order.orderId,t),C(l(Mm.SubmitOrderSucceeded,e.body.data,Object.assign(Object.assign({},e.body.meta),{token:e.headers.token}))))))}).pipe(P(e=>Ke(Mm.SubmitOrderFailed,e))))}finalizeOrder(e,t){return g(C(l(Mm.FinalizeOrderRequested)),_(this._orderRequestSender.finalizeOrder(e,t)).pipe(M(n=>g(this.loadOrder(e,t),C(l(Mm.FinalizeOrderSucceeded,n.body.data)))))).pipe(P(e=>Ke(Mm.FinalizeOrderFailed,e)))}_getCurrentOrderId(e){const t=e.order.getOrder(),n=e.checkout.getCheckout();return t&&t.orderId||n&&n.orderId}_mapToOrderRequestBody(e,t,n,i){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);return r?Object.assign(Object.assign({},o),{cartId:t,customerMessage:n,externalSource:i,payment:{paymentData:r.paymentData,name:r.methodId,gateway:r.gatewayId}}):Object.assign(Object.assign({},o),{cartId:t,customerMessage:n,externalSource:i})}}function Gm(e){const t=ke();return e.subscribe(e=>{const n=e.config.getStoreConfig();n&&t.setHost(n.paymentSettings.bigpayBaseUrl)},e=>e.config.getStoreConfig()),t}!function(e){e.LoadPaymentMethodRequested="LOAD_PAYMENT_METHOD_REQUESTED",e.LoadPaymentMethodSucceeded="LOAD_PAYMENT_METHOD_SUCCEEDED",e.LoadPaymentMethodFailed="LOAD_PAYMENT_METHOD_FAILED",e.LoadPaymentMethodsRequested="LOAD_PAYMENT_METHODS_REQUESTED",e.LoadPaymentMethodsSucceeded="LOAD_PAYMENT_METHODS_SUCCEEDED",e.LoadPaymentMethodsFailed="LOAD_PAYMENT_METHODS_FAILED"}(qm||(qm={}));const Hm=e=>!!e;class Wm{constructor(e){this._requestSender=e}loadPaymentMethodsById(e,t){return n=>new m(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodsRequested)),Promise.all(e.map(e=>{return n=this,i=void 0,o=function*(){try{return(yield this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a}))).body}catch(e){return}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).then(e=>{const t=e.filter(Hm);i.next(l(qm.LoadPaymentMethodsSucceeded,t)),i.complete()}).catch(e=>{i.next(l(qm.LoadPaymentMethodsFailed,e)),i.complete()})})}loadPaymentMethods(e){return t=>m.create(n=>{const i=t.getState().cart.getCartOrThrow();n.next(l(qm.LoadPaymentMethodsRequested)),this._requestSender.loadPaymentMethods(Object.assign(Object.assign({},e),{params:Object.assign(Object.assign({},null==e?void 0:e.params),{cartId:i.id})})).then(e=>{const t={deviceSessionId:e.headers["x-device-session-id"],sessionHash:e.headers["x-session-hash"]},i=e.body;n.next(l(qm.LoadPaymentMethodsSucceeded,i,t)),n.complete()}).catch(e=>{n.error(h(qm.LoadPaymentMethodsFailed,e))})})}loadPaymentMethod(e,t){return n=>m.create(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodRequested,void 0,{methodId:e})),this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a})).then(t=>{i.next(l(qm.LoadPaymentMethodSucceeded,t.body,{methodId:e})),i.complete()}).catch(t=>{i.error(h(qm.LoadPaymentMethodFailed,t,{methodId:e}))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Ct],Wm.prototype,"loadPaymentMethod",null);class $m{constructor(e){this._requestSender=e}loadPaymentMethods({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/payments",{timeout:e,headers:Object.assign({Accept:lt.JsonV1,"X-API-INTERNAL":Tt},et),params:t})}loadPaymentMethod(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this._requestSender.get(i,{timeout:t,headers:Object.assign({Accept:lt.JsonV1,"X-API-INTERNAL":Tt},et),params:n})}}class Ym extends rt{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var Km,Jm;!function(e){e.ExecuteFailed="PAYMENT_STRATEGY_EXECUTE_FAILED",e.ExecuteRequested="PAYMENT_STRATEGY_EXECUTE_REQUESTED",e.ExecuteSucceeded="PAYMENT_STRATEGY_EXECUTE_SUCCEEDED",e.FinalizeFailed="PAYMENT_STRATEGY_FINALIZE_FAILED",e.FinalizeRequested="PAYMENT_STRATEGY_FINALIZE_REQUESTED",e.FinalizeSucceeded="PAYMENT_STRATEGY_FINALIZE_SUCCEEDED",e.InitializeFailed="PAYMENT_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="PAYMENT_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="PAYMENT_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED"}(Km||(Km={})),function(e){e.ADYENV2="adyenv2",e.ADYENV2_GOOGLEPAY="googlepayadyenv2",e.ADYENV3="adyenv3",e.ADYENV3_GOOGLEPAY="googlepayadyenv3",e.AFFIRM="affirm",e.AFTERPAY="afterpay",e.AUTHORIZENET_GOOGLE_PAY="googlepayauthorizenet",e.AMAZONPAY="amazonpay",e.APPLEPAY="applepay",e.BLUESNAPV2="bluesnapv2",e.BOLT="bolt",e.CBA_MPGS="cba_mpgs",e.CHECKOUTCOM="checkoutcom",e.CHECKOUTCOM_APM="checkoutcomapm",e.CHECKOUTCOM_FAWRY="checkoutcomfawry",e.CHECKOUTCOM_SEPA="checkoutcomsepa",e.CHECKOUTCOM_IDEAL="checkoutcomideal",e.CREDIT_CARD="creditcard",e.CHECKOUTCOM_GOOGLE_PAY="googlepaycheckoutcom",e.CLEARPAY="clearpay",e.CONVERGE="converge",e.CYBERSOURCE="cybersource",e.CYBERSOURCEV2="cybersourcev2",e.BNZ="bnz",e.BNZ_GOOGLEPAY="googlepaybnz",e.CYBERSOURCEV2_GOOGLE_PAY="googlepaycybersourcev2",e.HUMM="humm",e.KLARNA="klarna",e.KLARNAV2="klarnav2",e.LEGACY="legacy",e.MOLLIE="mollie",e.MONERIS="moneris",e.NO_PAYMENT_DATA_REQUIRED="nopaymentdatarequired",e.OFFLINE="offline",e.OFFSITE="offsite",e.ORBITAL_GOOGLE_PAY="googlepayorbital",e.PAYPAL_EXPRESS="paypalexpress",e.PAYPAL_EXPRESS_CREDIT="paypalexpresscredit",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARD="paypalcommercecreditcards",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo",e.PPSDK="PAYMENT_TYPE_SDK",e.QUADPAY="quadpay",e.SAGE_PAY="sagepay",e.SQUARE="squarev2",e.STRIPEV3="stripev3",e.STRIPE_UPE="stripeupe",e.STRIPE_UPE_GOOGLE_PAY="googlepaystripeupe",e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISA_CHECKOUT="braintreevisacheckout",e.BRAINTREE_GOOGLE_PAY="googlepaybraintree",e.WE_PAY="wepay",e.WORLDPAYACCESS="worldpayaccess",e.WORLDPAYACCESS_GOOGLE_PAY="googlepayworldpayaccess",e.STRIPE_GOOGLE_PAY="googlepaystripe",e.SEZZLE="sezzle",e.ZIP="zip"}(Jm||(Jm={}));const Zm=Jm;class Qm{widgetInteraction(e,t){const n={methodId:t&&t.methodId};return g(C(l(Km.WidgetInteractionStarted,void 0,n)),f(()=>e().then(()=>l(Km.WidgetInteractionFinished,void 0,n)))).pipe(P(e=>Ke(Km.WidgetInteractionFailed,e,n)))}}class Xm{constructor(e,t,n,i,r){this._strategyRegistry=e,this._strategyRegistryV2=t,this._orderActionCreator=n,this._spamProtectionActionCreator=i,this._paymentIntegrationService=r,this._paymentStrategyWidgetActionCreator=new Qm}execute(e,t){const{payment:n={},useStoreCredit:i}=e,r={methodId:n.methodId};return o=>{const{checkout:a}=o.getState(),{shouldExecuteSpamCheck:s}=a.getCheckoutOrThrow();return g(s?this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(o):v(),C(l(Km.ExecuteRequested,void 0,r)),f(()=>{const a=o.getState();let s;if(a.payment.isPaymentDataRequired(i)){const e=a.paymentMethods.getPaymentMethod(n.methodId,n.gatewayId);if(!e)throw new ot(tt.MissingPaymentMethod);s=this._getStrategy(e)}else s=this._strategyRegistryV2.get({id:Zm.NO_PAYMENT_DATA_REQUIRED});return s.execute(e,Object.assign(Object.assign({},t),{methodId:n.methodId,gatewayId:n.gatewayId})).then(()=>l(Km.ExecuteSucceeded,void 0,r))})).pipe(P(e=>Ke(Km.ExecuteFailed,e,r)))}}finalize(e){const{integrations:t}=null!=e?e:{};return n=>g(C(l(Km.FinalizeRequested)),this._loadOrderPaymentsIfNeeded(n,e),f(()=>{return i=this,r=void 0,a=function*(){const i=n.getState(),{providerId:r="",gatewayId:o=""}=i.payment.getPaymentId()||{},a=i.paymentMethods.getPaymentMethod(r,o);if(!a)throw new Ym;let s;Qt(this._strategyRegistryV2,null!=t?t:[],this._paymentIntegrationService);try{s=this._getStrategy(a)}catch(e){throw new Ym}return yield s.finalize(Object.assign(Object.assign({},e),{methodId:a.id,gatewayId:a.gateway})),l(Km.FinalizeSucceeded,void 0,{methodId:a.id})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>{const t=n.getState().payment.getPaymentId();return Ke(Km.FinalizeFailed,e,{methodId:t&&t.providerId})}))}initialize(e){const{methodId:t,gatewayId:n,integrations:i}=e;return r=>f(()=>{const o=r.getState(),a=o.paymentMethods.getPaymentMethod(t,n);if(!a)throw new ot(tt.MissingPaymentMethod);if(t&&o.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return v();Qt(this._strategyRegistryV2,null!=i?i:[],this._paymentIntegrationService);const s=this._getStrategy(a).initialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.InitializeRequested,void 0,{methodId:t,gatewayId:n})),s.then(()=>l(Km.InitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Ke(Km.InitializeFailed,e,{methodId:t,gatewayId:n})))}deinitialize(e){const{methodId:t,gatewayId:n}=e;return i=>f(()=>{const r=i.getState(),o=r.paymentMethods.getPaymentMethod(t,n);if(!o)throw new ot(tt.MissingPaymentMethod);if(t&&!r.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return v();const a=this._getStrategy(o).deinitialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.DeinitializeRequested,void 0,{methodId:t,gatewayId:n})),a.then(()=>l(Km.DeinitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Ke(Km.DeinitializeFailed,e,{methodId:t,gatewayId:n})))}widgetInteraction(e,t){return this._paymentStrategyWidgetActionCreator.widgetInteraction(e,t)}_getStrategy(e){let t;try{t=this._strategyRegistry.getByMethod(e)}catch(n){try{t=this._strategyRegistryV2.get({id:e.id,gateway:e.gateway,type:e.type})}catch(t){throw wt().error(`[PaymentStrategyActionCreator] Unable to resolve V2 strategy for id: ${e.id}, gateway: ${e.gateway}, type: ${e.type}`),t}}return t}_loadOrderPaymentsIfNeeded(e,t){const n=e.getState().checkout.getCheckout();return n&&n.orderId?this._orderActionCreator.loadOrderPayments(n.orderId,t):v()}}class ey{isEqual(e,t){return Y(this._normalize(e),this._normalize(t))}_normalize(e){return{cartAmount:e.cartAmount,currency:e.currency,id:e.id,lineItems:{digitalItems:e.lineItems.digitalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId})),giftCertificates:e.lineItems.giftCertificates.slice().sort((e,t)=>`${e.id}`.localeCompare(`${t.id}`)).map(e=>({amount:e.amount,recipient:e.recipient})),physicalItems:e.lineItems.physicalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId,giftWrapping:e.giftWrapping}))}}}}class ty extends rt{constructor(e,t){super("An update to your shopping cart has been detected and your available shipping costs have been updated."),this.name="CartChangedError",this.type="cart_changed",this.data={previous:e,updated:t}}}class ny{constructor(e){this._checkoutRequestSender=e}validate(e,t){if(!e)throw new ot(tt.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then(t=>{const n=new ey;if(!(e.outstandingBalance===t.body.outstandingBalance&&this._compareCoupons(e.coupons,t.body.coupons)&&this._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&n.isEqual(e.cart,t.body.cart)))throw new ty(this._getComparableCheckout(e),this._getComparableCheckout(t.body))})}_compareCoupons(e,t){return Y(oe(e,"code"),oe(t,"code"))}_compareGiftCertificates(e,t){return Y(oe(e,"code"),oe(t,"code"))}_getComparableCheckout(e){const{cart:t,coupons:n,giftCertificates:i,outstandingBalance:r}=e;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:n,giftCertificates:i,outstandingBalance:r}}}class iy{constructor(e){this._namespace=e}getItem(e){const t=Te.getItem(this.withNamespace(e));if(null===t)return null;try{return JSON.parse(t)}catch(t){return this.removeItem(this.withNamespace(e)),null}}getItemOnce(e){const t=this.getItem(e);return this.removeItem(e),t}setItem(e,t){return Te.setItem(this.withNamespace(e),JSON.stringify(t))}removeItem(e){return Te.removeItem(this.withNamespace(e))}withNamespace(e){return`${this._namespace}.${e}`}}class ry extends rt{constructor(){super("Please complete our human verification challenge and try again."),this.name="CardingProtectionChallengeNotCompletedError",this.type="carding_protection_challenge_not_completed"}}class oy extends rt{constructor(){super("We were not able to verify that you are not a robot. Please try again."),this.name="CardingProtectionFailedError",this.type="carding_protection_failed"}}var ay,sy,dy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cy{constructor(e){this._googleRecaptcha=e}handle(e,t){return dy(this,void 0,void 0,function*(){return"string"==typeof e?this.handleWithRecaptchaSitekey(e,t):this.handleWithPaymentHumanVerificationRequestError(e)})}handleWithPaymentHumanVerificationRequestError(e){return dy(this,void 0,void 0,function*(){if(!this._isPaymentHumanVerificationRequest(e))throw e;return yield this._initialize(e.body.additional_action_required.data.key),this._performRecaptcha()})}handleWithRecaptchaSitekey(e,t){return dy(this,void 0,void 0,function*(){if("recaptcha_v2"!==e)throw Error("Human verification method is not supported.");if(!t)throw Error("Recaptcha site key is missing.");return yield this._initialize(t),this._performRecaptcha()})}_performRecaptcha(){return this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>dy(this,void 0,void 0,function*(){if(e instanceof dn)throw new ry;if(e||!t)throw new oy;return{type:"recaptcha_v2_verification",data:{human_verification_token:t}}}))).toPromise()}_initialize(e){const t="cardingProtectionContainer";let n=document.getElementById(t);return n&&n.parentNode&&n.parentNode.removeChild(n),n=document.createElement("div"),n.setAttribute("id",t),document.body.appendChild(n),this._googleRecaptcha.load(t,e)}_isPaymentHumanVerificationRequest(e){const{additional_action_required:t,status:n}=e.body||{};return"additional_action_required"===n&&t&&"recaptcha_v2_verification"===t.type}}function ly(e,t){const{body:n}=e,{errors:i=[]}=n;return new Et(e,{message:uy(i)||t,errors:i})}function uy(e){if(Array.isArray(e))return e.reduce((e,t)=>t&&t.message?[...e,t.message]:e,[]).join(" ")}class hy extends rt{constructor(e){super(e||"Unable to proceed due to invalid configuration provided for the hosted payment form."),this.name="InvalidHostedFormConfigError",this.type="invalid_hosted_form_config"}}class py extends rt{constructor(e){super(e||"Unable to proceed due to an unknown error with the hosted payment form."),this.name="InvalidHostedFormError",this.type="invalid_hosted_form"}}class my extends rt{constructor(e){super(["Unable to proceed due to invalid user input values",...U(Ce(e),e=>oe(e,({message:e})=>e))].join(". ")),this.errors=e,this.name="InvalidHostedFormValueError",this.type="invalid_hosted_form_value"}}!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED",e.StoredCardRequested="HOSTED_FIELD:STORED_CARD_REQUESTED"}(ay||(ay={})),function(e){e.AttachSucceeded="HOSTED_INPUT:ATTACH_SUCCEEDED",e.AttachFailed="HOSTED_INPUT:ATTACH_FAILED",e.BinChanged="HOSTED_INPUT:BIN_CHANGED",e.Blurred="HOSTED_INPUT:BLURRED",e.Changed="HOSTED_INPUT:CHANGED",e.CardTypeChanged="HOSTED_INPUT:CARD_TYPE_CHANGED",e.Entered="HOSTED_INPUT:ENTERED",e.Focused="HOSTED_INPUT:FOCUSED",e.SubmitSucceeded="HOSTED_INPUT:SUBMIT_SUCCEEDED",e.SubmitFailed="HOSTED_INPUT:SUBMIT_FAILED",e.Validated="HOSTED_INPUT:VALIDATED",e.StoredCardSucceeded="HOSTED_INPUT:STORED_CARD_SUCCEEDED",e.StoredCardFailed="HOSTED_INPUT:STORED_CARD_FAILED"}(sy||(sy={}));var yy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class gy{constructor(e,t,n,i,r,o,a,s,d,c){this._type=e,this._containerId=t,this._placeholder=n,this._accessibilityLabel=i,this._styles=r,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=s,this._checkoutId=d,this._cardInstrument=c,this._iframe=document.createElement("iframe");const l=this._checkoutId?`/checkout/payment/hosted-field?version=1.904.1&checkoutId=${this._checkoutId}`:"/checkout/payment/hosted-field?version=1.904.1";this._iframe.src=l,this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}getType(){return this._type}attach(){return yy(this,void 0,void 0,function*(){const e=document.getElementById(this._containerId);if(!e)throw new hy("Unable to proceed because the provided container ID is not valid.");e.appendChild(this._iframe),this._eventListener.listen();const t=S(this._iframe,"load").pipe(M(({target:e})=>yy(this,void 0,void 0,function*(){const t=e&&e.contentWindow;if(!t)throw new Error("The content window of the iframe cannot be accessed.");this._eventPoster.setTarget(t),yield this._eventPoster.post({type:ay.AttachRequested,payload:{accessibilityLabel:this._accessibilityLabel,cardInstrument:this._cardInstrument,fontUrls:this._getFontUrls(),placeholder:this._placeholder,styles:this._styles,origin:document.location.origin,type:this._type}},{successType:sy.AttachSucceeded,errorType:sy.AttachFailed})})),z(1)).toPromise();yield this._detachmentObserver.ensurePresence([this._iframe],t)})}detach(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())}submitForm(e,t){return yy(this,void 0,void 0,function*(){try{const n=this._eventPoster.post({type:ay.SubmitRequested,payload:{fields:e,data:t}},{successType:sy.SubmitSucceeded,errorType:sy.SubmitFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],n)}catch(e){if(this._isSubmitErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new py(e.payload.error.message);if(e.payload.response)throw ly(e.payload.response);throw new Error(e.payload.error.message)}throw e}})}submitStoredCardForm(e,t){return yy(this,void 0,void 0,function*(){const n=this._eventPoster.post({type:ay.StoredCardRequested,payload:{fields:e,data:t}},{successType:sy.StoredCardSucceeded,errorType:sy.StoredCardFailed});return this._detachmentObserver.ensurePresence([this._iframe],n)})}validateForm(){return yy(this,void 0,void 0,function*(){const e=this._eventPoster.post({type:ay.ValidateRequested},{successType:sy.Validated}),{payload:t}=yield this._detachmentObserver.ensurePresence([this._iframe],e);if(!t.isValid)throw new my(t.errors)})}_getFontUrls(){const e="fonts.googleapis.com",t=document.querySelectorAll(`link[href*='${e}'][rel='stylesheet']`);return Array.prototype.slice.call(t).filter(t=>Cn(t.href).hostname===e).filter(e=>Ce(this._styles).map(e=>e&&e.fontFamily).filter(e=>"string"==typeof e).some(t=>t.split(/,\s/).some(t=>-1!==e.href.indexOf(t.replace(" ","+"))))).map(e=>e.href)}_isSubmitErrorEvent(e){return e.type===sy.SubmitFailed}}var fy,vy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _y{constructor(e,t,n,i,r){this._fields=e,this._eventListener=t,this._payloadTransformer=n,this._eventCallbacks=i,this._paymentHumanVerificationHandler=r,this._handleEnter=({payload:e})=>vy(this,void 0,void 0,function*(){try{yield this.validate()}catch(e){if(e instanceof Error&&"InvalidHostedFormValueError"!==e.name)throw e}const{onEnter:t=ce}=this._eventCallbacks;t(e)});const{onBlur:o=ce,onCardTypeChange:a=ce,onFocus:s=ce,onValidate:d=ce}=this._eventCallbacks;this._eventListener.addListener(sy.Blurred,({payload:e})=>o(e)),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>a(e)),this._eventListener.addListener(sy.Focused,({payload:e})=>s(e)),this._eventListener.addListener(sy.Validated,({payload:e})=>d(e)),this._eventListener.addListener(sy.Entered,this._handleEnter),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>this._cardType=e.cardType),this._eventListener.addListener(sy.BinChanged,({payload:e})=>this._bin=e.bin)}getBin(){return this._bin}getCardType(){return this._cardType}attach(){return vy(this,void 0,void 0,function*(){this._eventListener.listen();const e=this._getFirstField(),t=be(this._fields,e);yield e.attach(),yield Promise.all(t.map(e=>e.attach()))})}detach(){this._eventListener.stopListen(),this._fields.forEach(e=>{e.detach()})}submit(e,t){return vy(this,void 0,void 0,function*(){try{return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,t))}catch(t){const n=yield this._paymentHumanVerificationHandler.handle(t);return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,n))}})}submitStoredCard(e){return vy(this,void 0,void 0,function*(){return this._getFirstField().submitStoredCardForm(e.fields,e.data)})}validate(){return vy(this,void 0,void 0,function*(){return this._getFirstField().validateForm()})}_getFirstField(){const e=this._fields[0];if(!e)throw new hy("Unable to proceed because the payment form has no field defined.");return e}}function Sy(e){return Boolean(e.instrumentId)}class Iy{constructor(e){this._store=e}transform(e,t){const n=this._store.getState(),i=n.checkout.getCheckout(),r=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),s=n.order.getOrderMeta(),d=le(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv");let c=n.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId);"worldpayaccess"===(null==c?void 0:c.gateway)&&"credit_card"===(null==c?void 0:c.id)&&(c=Object.assign(Object.assign({},c),{id:"worldpayaccess",method:"credit-card"}));const l=n.paymentMethods.getPaymentMethodsMeta(),u=o&&d&&Sy(d)?`${n.payment.getPaymentToken()}, ${o.vaultAccessToken}`:n.payment.getPaymentToken();if(!u)throw new ot(tt.MissingPaymentToken);return{additionalAction:t,authToken:u,checkout:i,config:r,order:a,orderMeta:s,payment:d,paymentMethod:c,paymentMethodMeta:l}}}class wy{constructor(e){this._store=e}create(e,t,n){const i=Object.keys(t.fields).reduce((i,r)=>{const o=t.fields[r];return o?[...i,new gy(r,o.containerId,o.placeholder||"",o.accessibilityLabel||"",t.styles||{},new On(e),new Kn(e),new Dn(new yn),n,"instrumentId"in o?this._getCardInstrument(o.instrumentId):void 0)]:i},[]);return new _y(i,new Kn(e),new Iy(this._store),pe(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new cy(Sn(o())))}_getCardInstrument(e){const{instruments:{getCardInstrument:t}}=this._store.getState(),n=t(e);if(!n)throw new ot(tt.MissingPaymentInstrument);return n}}!function(e){e.SubmitPaymentRequested="SUBMIT_PAYMENT_REQUESTED",e.SubmitPaymentSucceeded="SUBMIT_PAYMENT_SUCCEEDED",e.SubmitPaymentFailed="SUBMIT_PAYMENT_FAILED",e.InitializeOffsitePaymentRequested="INITIALIZE_OFFSITE_PAYMENT_REQUESTED",e.InitializeOffsitePaymentSucceeded="INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED",e.InitializeOffsitePaymentFailed="INITIALIZE_OFFSITE_PAYMENT_FAILED"}(fy||(fy={}));class Cy{constructor(e,t,n,i){this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=i,this.initializeOffsitePayment=({methodId:e,gatewayId:t,instrumentId:n,target:i,promise:r,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})=>s=>{let d;n?d={formattedPayload:{bigpay_token:n}}:o&&(d={formattedPayload:{vault_payment_instrument:o,set_as_default_stored_instrument:a||null}});const c=this._paymentRequestTransformer.transform({gatewayId:t,methodId:e,paymentData:d},s.getState());return g(C(l(fy.InitializeOffsitePaymentRequested)),Promise.race([this._paymentRequestSender.initializeOffsitePayment(c,i),r].filter(Boolean)).then(()=>l(fy.InitializeOffsitePaymentSucceeded))).pipe(P(e=>Ke(fy.InitializeOffsitePaymentFailed,e)))}}submitPayment(e){return t=>g(C(l(fy.SubmitPaymentRequested)),f(()=>{return n=this,i=void 0,o=function*(){try{return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,t.getState()))}catch(n){const i=yield this._paymentHumanVerificationHandler.handle(n);return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(Object.assign(Object.assign({},e),{additionalAction:i}),t.getState()))}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}).pipe(M(({body:e})=>g(this._orderActionCreator.loadCurrentOrder()(t),C(l(fy.SubmitPaymentSucceeded,e)))))).pipe(P(e=>Ke(fy.SubmitPaymentFailed,e)))}}class by{constructor(e){this._client=e}submitPayment(e){return new Promise((t,n)=>{this._client.submitPayment(e,(e,i)=>{e?n(this._transformResponse(e)):t(this._transformResponse(i))})})}initializeOffsitePayment(e,t){return new Promise(()=>{this._client.initializeOffsitePayment(e,null,t)})}_transformResponse(e){return{headers:e.headers,body:e.data,status:e.status,statusText:e.statusText}}}function Py(e,t){let n;return function(e){return void 0!==e.id}(e)?n=e.id:t&&t.length&&(n=t[0].id),{id:n,firstName:e.firstName,lastName:e.lastName,company:e.company,addressLine1:e.address1,addressLine2:e.address2,city:e.city,province:e.stateOrProvince,provinceCode:e.stateOrProvinceCode,postCode:e.postalCode,country:e.country,countryCode:e.countryCode,phone:e.phone,customFields:e.customFields}}const Oy=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function Ey(e){return{code:e.code,discount:e.displayName,discountType:Oy.indexOf(e.couponType)}}function Ay(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function Ty(e){const t=[];return(e||[]).forEach(e=>{(e.banners||[]).forEach(e=>{t.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})})}),t}function ky(e,t,n="id"){return Object.keys(e).reduce((i,r)=>[...i,...e[r].map(e=>"giftCertificates"===r?function(e,t){const n=new vd(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:n.toInteger(e.amount),integerAmountAfterDiscount:n.toInteger(e.amount),integerUnitPrice:n.toInteger(e.amount),integerUnitPriceAfterDiscount:n.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,n,i="id"){const r=new vd(n);return{id:e[i],imageUrl:e.imageUrl,amount:e.extendedListPrice,amountAfterDiscount:e.extendedSalePrice,discount:e.discountAmount,integerAmount:r.toInteger(e.extendedListPrice),integerAmountAfterDiscount:r.toInteger(e.extendedSalePrice),integerDiscount:r.toInteger(e.discountAmount),integerUnitPrice:r.toInteger(e.listPrice),integerUnitPriceAfterDiscount:r.toInteger(e.salePrice),downloadsPageUrl:e.downloadPageUrl,name:e.name,quantity:e.quantity,brand:e.brand,sku:e.sku,categoryNames:e.categoryNames,variantId:e.variantId,productId:e.productId,attributes:(e.options||[]).map(e=>({name:e.name,value:e.value})),addedByPromotion:e.addedByPromotion,type:t}}(e,function(e){switch(e){case"physicalItems":return"ItemPhysicalEntity";case"digitalItems":return"ItemDigitalEntity";case"giftCertificates":return"ItemGiftCertificateEntity";default:return""}}(r),t,n))],[])}function Dy(e){const t=e.cart.currency.decimalPlaces,n=new vd(t);return{id:e.cart.id,items:ky(e.cart.lineItems,t),currency:e.cart.currency.code,coupon:{discountedAmount:ye(e.cart.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.cart.coupons.map(Ey)},discount:{amount:e.cart.discountAmount,integerAmount:n.toInteger(e.cart.discountAmount)},discountNotifications:Ty(e.promotions),giftCertificate:{totalDiscountedAmount:ye(e.giftCertificates,(e,t)=>e+t.used,0),appliedGiftCertificates:ne(e.giftCertificates.map(Ay),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:n.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:n.toInteger(e.shippingCostBeforeDiscount),required:fe(e.cart.lineItems.physicalItems,e=>e.isShippingRequired)},subtotal:{amount:e.subtotal,integerAmount:n.toInteger(e.subtotal)},storeCredit:{amount:e.customer?e.customer.storeCredit:0},taxSubtotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:n.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.grandTotal,integerAmount:n.toInteger(e.grandTotal)}}}var My;!function(e){e.APPLEPAY="applepay",e.AMAZON_PAY_V2="amazonpay",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.GOOGLEPAY_ADYENV2="googlepayadyenv2",e.GOOGLEPAY_ADYENV3="googlepayadyenv3",e.GOOGLEPAY_AUTHORIZENET="googlepayauthorizenet",e.GOOGLEPAY_BNZ="googlepaybnz",e.GOOGLEPAY_BRAINTREE="googlepaybraintree",e.GOOGLEPAY_CHECKOUTCOM="googlepaycheckoutcom",e.GOOGLEPAY_CYBERSOURCEV2="googlepaycybersourcev2",e.GOOGLEPAY_ORBITAL="googlepayorbital",e.GOOGLEPAY_STRIPE="googlepaystripe",e.GOOGLEPAY_STRIPEUPE="googlepaystripeupe",e.GOOGLEPAY_WORLDPAYACCESS="googlepayworldpayaccess",e.PAYPALEXPRESS="paypalexpress"}(My||(My={}));const zy=My;function xy(e,t){const n=e.firstName||t.firstName||"",i=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map(e=>Py(e)),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:n,lastName:i,name:e.fullName||[n,i].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}class Ny{format(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*")),i=t.slice(0,2),r=4===n.length?n.slice(-2):n?n.slice(0,2):t.slice(2);return e.length<2?t:e.length>3&&!r?i:`${i} / ${r}`}toObject(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*"));return/^\d+$/.test(t)&&/^\d+$/.test(n)?{month:1===t.length?`0${t}`:t.slice(0,2),year:2===n.length?`20${n}`:n.slice(0,4)}:{month:"",year:""}}}class Ry{format(e){const{card:t}=Me(e);if(!t)return e;const n=ae(De(e).map(e=>ae(e.lengths))),i=this.unformat(e).slice(0,n);return t.gaps.filter(e=>i.length>e).reduce((e,t,n)=>[e.slice(0,t+n),e.slice(t+n)].join(" "),i)}unformat(e){const{card:t}=Me(e);return t?e.replace(new RegExp(" ","g"),""):e}}function Fy(e,t={}){const n=e.currency.decimalPlaces,i=new vd(n);return{id:e.orderId,items:ky(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:By(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:i.toInteger(e.baseAmount)},coupon:{discountedAmount:ye(e.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.coupons.map(Ey)},discount:{amount:e.discountAmount,integerAmount:i.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:jy(e.payments),socialData:qy(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:Ly(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:i.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:i.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function Ly(e){const t=j(e,{providerId:"storecredit"});return t?t.amount:0}function jy(e){const t=L(e,{providerId:"giftcertificate"});return{totalDiscountedAmount:ye(t,(e,t)=>t.amount+e,0),appliedGiftCertificates:ne(t.map(e=>({code:e.detail.code,discountedAmount:e.amount,remainingBalance:e.detail.remaining,giftCertificate:{balance:e.amount+e.detail.remaining,code:e.detail.code,purchaseDate:""}})),"code")}}function By(e,t={}){const n=j(e,Uy);return n?{id:n.providerId,status:(i=n.detail.step,`PAYMENT_STATUS_${i}`),helpText:n.detail.instructions,returnUrl:t.returnUrl}:{};var i}function Uy(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function qy(e){const t={};return[...e.lineItems.physicalItems,...e.lineItems.digitalItems].forEach(e=>{var n;t[e.id]=(n=e,["fb","tw","gp"].reduce((e,t)=>{const i=n.socialMedia&&j(n.socialMedia,e=>e.code===t);return i?(e[t]={name:n.name,description:n.name,image:n.imageUrl,url:i.link,shareText:i.text,sharingLink:i.link,channelName:i.channel,channelCode:i.code},e):e},{}))}),t}function Vy(e,t){return{description:e.description,module:e.type,price:e.cost,id:e.id,selected:t,isRecommended:e.isRecommended,imageUrl:e.imageUrl,transitTime:e.transitTime}}class Gy{constructor(){this._cardExpiryFormatter=new Ny,this._cardNumberFormatter=new Ry}transform(e,t){const n=t.billingAddress.getBillingAddress(),i=t.checkout.getCheckout(),r=t.customer.getCustomer(),o=t.order.getOrder(),a=t.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),s=this._mapShippingAddress(t,a),d=t.consignments.getConsignments(),c=t.consignments.getShippingOption(),l=t.config.getStoreConfig(),u=t.config.getContextConfig(),h=t.instruments.getInstrumentsMeta(),p=t.paymentMethods.getPaymentMethodsMeta(),m=t.order.getOrderMeta(),y=r&&n&&xy(r,n),g=h&&e.paymentData&&(Sy(e.paymentData)||function(e){const t=e.formattedPayload;return!!t&&("string"==typeof t.bigpay_token||Boolean(t.bigpay_token&&t.bigpay_token.token))}(e.paymentData))?`${t.payment.getPaymentToken()}, ${h.vaultAccessToken}`:t.payment.getPaymentToken();if(!g)throw new ot(tt.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:g,customer:y,billingAddress:n&&Py(n),shippingAddress:s&&Py(s,d),shippingOption:c&&Vy(c,!0),cart:i&&Dy(i),order:o&&Fy(o,m),orderMeta:m,payment:e.paymentData,paymentMethod:a&&this._transformPaymentMethod(a),quoteMeta:{request:Object.assign(Object.assign({},p),{geoCountryCode:u&&u.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:pe(l&&l.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}transformWithHostedFormData(e,t,n){const{additionalAction:i,authToken:r,checkout:o,config:a,order:s,orderMeta:d,payment:c={},paymentMethod:l,paymentMethodMeta:u}=t,h=o&&o.consignments[0],p=h&&h.shippingAddress,m=h&&h.selectedShippingOption;return{additionalAction:i,authToken:r,paymentMethod:l&&this._transformPaymentMethod(l),customer:s&&s.billingAddress&&o&&xy(o.customer,s.billingAddress),billingAddress:s&&s.billingAddress&&Py(s.billingAddress),shippingAddress:p&&o&&Py(p,o.consignments),shippingOption:m&&Vy(m,!0),cart:o&&Dy(o),order:s&&Fy(s,d),orderMeta:d,payment:this._transformHostedInputValues(e,c,n),quoteMeta:{request:Object.assign(Object.assign({},u),{geoCountryCode:a&&a.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:a&&pe(a.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}_transformPaymentMethod(e){return"multi-option"!==e.method||e.gateway?e.initializationData&&e.initializationData.gateway?Object.assign(Object.assign({},e),{id:e.initializationData.gateway}):"worldpayaccess"===e.gateway&&"credit_card"===e.id?Object.assign(Object.assign({},e),{id:"worldpayaccess",method:"credit-card"}):e.id===zy.BRAINTREE_VENMO?Object.assign(Object.assign({},e),{id:zy.BRAINTREE_PAYPAL}):e:Object.assign(Object.assign({},e),{gateway:e.id})}_transformHostedInputValues(e,t,n){return"instrumentId"in t?Object.assign(Object.assign({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:n}):Object.assign(Object.assign({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:n})}_mapShippingAddress(e,t){var n,i,r,o;if(t){const a=null===(i=null===(n=t.initializationData)||void 0===n?void 0:n.bopis)||void 0===i?void 0:i.enabled,s=null===(o=null===(r=t.initializationData)||void 0===r?void 0:r.bopis)||void 0===o?void 0:o.requiredAddress,d=e.consignments.getConsignments(),c=null==d?void 0:d.every(e=>e.selectedPickupOption);if(a&&c&&"none"===s)return}return e.shippingAddress.getShippingAddress()}}const Hy=e=>{const{type:t,initializationStrategy:n}=e;return t===Zm.PPSDK&&"string"==typeof(null==n?void 0:n.type)};class Wy extends Gt{getByMethod(e){if(!e)return this.get();const t=this._getToken(e),n=[e.gateway,e.id].filter(e=>null!=e).join("-");return this.get(t,n)}_getToken(e){if(Hy(e))return Zm.PPSDK;if("klarna"===e.gateway)return Zm.KLARNAV2;const t=e.gateway||e.id;if(this._hasFactoryForMethod(t))return t;if("PAYMENT_TYPE_OFFLINE"===e.type)return Zm.OFFLINE;throw new Vt(`'${t}' is not registered.`)}_hasFactoryForMethod(e){return this._hasFactory(e)}}const $y="FINALIZE";class Yy extends Vt{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"}}var Ky=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n};class Jy{constructor(e,t,n,i){this._store=e,this._orderActionCreator=t,this._paymentActionCreator=n,this._hostedFormFactory=i}execute(e,t){var n,i;return this._isHostedPaymentFormEnabled(null===(n=e.payment)||void 0===n?void 0:n.methodId,null===(i=e.payment)||void 0===i?void 0:i.gatewayId)&&this._shouldRenderHostedForm?this._executeWithHostedForm(e,t):this._executeWithoutHostedForm(e,t)}finalize(e){return Promise.reject(new Ym)}initialize(e){if(!this._isHostedPaymentFormEnabled(null==e?void 0:e.methodId,null==e?void 0:e.gatewayId)||!this._isHostedFieldAvailable(e))return this._shouldRenderHostedForm=!1,Promise.resolve(this._store.getState());const t=e&&e.creditCard&&e.creditCard.form,{config:n}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:i=""}={}}=n.getStoreConfig()||{};if(!t)throw new Vt;const r=this._hostedFormFactory.create(i,t);return r.attach().then(()=>(this._shouldRenderHostedForm=!0,this._hostedForm=r,this._store.getState()))}deinitialize(e){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve(this._store.getState())}_executeWithoutHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new Yy(["payment.paymentData"]);return this._store.dispatch(this._orderActionCreator.submitOrder(i,t)).then(()=>this._store.dispatch(this._paymentActionCreator.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))))}_executeWithHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=this._hostedForm;if(!r)throw new gn(ln.PaymentNotInitialized);if(!n||!n.methodId)throw new Yy(["payment.methodId"]);return r.validate().then(()=>this._store.dispatch(this._orderActionCreator.submitOrder(i,t))).then(()=>r.submit(n)).then(()=>this._store.dispatch(this._orderActionCreator.loadCurrentOrder()))}_isHostedPaymentFormEnabled(e,t){if(!e)return!1;const{paymentMethods:{getPaymentMethodOrThrow:n}}=this._store.getState();return!0===n(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}class Zy extends Jy{constructor(e,t,n,i,r){super(e,t,n,i),this._formPoster=r}execute(e,t){return super.execute(e,t).catch(e=>e instanceof Et&&fe(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{this._formPoster.postForm(e.body.three_ds_result.acs_url,{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data})}):Promise.reject(e))}finalize(e){const t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===$y?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Ym)}}class Qy extends rt{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}const Xy="redirecting";class eg{constructor(){this._isRedirecting=this.currentUrlHasRedirectingParam()}isRedirecting(){return this._isRedirecting}setRedirecting(e){e?this.setRedirectingParamOnUrl():this.removeRedirectingParamFromUrl(),this._isRedirecting=e}currentUrlHasRedirectingParam(){return Xy in this.getCurrentUrl().query}getCurrentUrl(){return xe(window.location.href)}replaceCurrentUrl(e){window.history.replaceState(null,"",e)}setRedirectingParamOnUrl(){if(this.currentUrlHasRedirectingParam())return;const e=this.getCurrentUrl(),t=Object.assign(Object.assign({},e),{query:Object.assign(Object.assign({},e.query),{[Xy]:"true"})});this.replaceCurrentUrl(Ne(t))}removeRedirectingParamFromUrl(){this.currentUrlHasRedirectingParam()&&this.replaceCurrentUrl(ze(window.location.href,[Xy]))}}const tg=he([e=>"continue"===V(e,"type")&&"redirect"===V(e,"code")&&(e=>{const t=V(e,"form_fields");return X(V(e,"url"))&&(ee(t)||Z(t))})(V(e,"parameters")),e=>"continue"===V(e,"type")&&"resubmit_with_human_verification"===V(e,"code")&&(e=>{const t=V(e,"available_methods");return W(t)})(V(e,"parameters"))]);class ng{constructor(e,t){this._formPoster=e,this._humanVerificationHandler=t}handle(e,t){switch(e.code){case"redirect":return(({url:e,form_fields:t},n)=>{const i=new eg;return i.isRedirecting()?(i.setRedirecting(!1),Promise.reject(new Qy)):(i.setRedirecting(!0),t?n.postForm(e,t):window.location.assign(e),new Promise(ce))})(e.parameters,this._formPoster);case"resubmit_with_human_verification":return(({available_methods:e},t,n)=>{return i=void 0,r=void 0,a=function*(){if(!n)throw new Error("PPSDK human verification callback function is missing.");if(!t)throw new Error("PPSDK human verification handler is missing.");if(0===e.length)throw Error("Human verification method is missing.");const{id:i,parameters:r}=e[0],o=yield t.handle(i,r.key);return n(o)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})(e.parameters,this._humanVerificationHandler,null==t?void 0:t.humanVerification)}}}class ig{constructor(e){this._continueHandler=e}handle(e,t){const{body:n}=e;return(e=>"success"===V(e,"type"))(n)?Promise.resolve():(e=>tg(e))(n)?this._continueHandler.handle(n,null==t?void 0:t.continue):(e=>"failure"===V(e.body,"type")&&X(V(e.body,"code")))(e)?(e=>{return Promise.reject(new Et((t=e,Object.assign(Object.assign({},t),{body:{errors:[{code:t.body.code}]}}))));var t})(e):((e=>{V(e.body,"type")})(e),(e=>Promise.reject(new Et(e)))(e))}}const rg="completed-payments";class og{constructor(e){this._browserStorage=e}isCompleted(e){return this.getCompletedPayments().indexOf(e)>=0}setCompleted(e){const t=this.getCompletedPayments();t.push(e),this.setCompletedPayments(t)}getCompletedPayments(){return this._browserStorage.getItem(rg)||[]}setCompletedPayments(e){this._browserStorage.setItem(rg,e)}}var ag,sg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class dg{constructor(e,t,n,i,r){this._store=e,this._orderActionCreator=t,this._subStrategyRegistry=n,this._paymentResumer=i,this._completedPayments=new og(r)}execute(e,t){var n;return sg(this,void 0,void 0,function*(){const{bigpayBaseUrl:i}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==t?void 0:t.methodId))throw new Vt('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:r}=t,{payment:o}=e,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{_subStrategy:s}=this;if(!s)throw new gn(ln.PaymentNotInitialized);yield this._store.dispatch(this._orderActionCreator.submitOrder(a,t));const d=null===(n=this._store.getState().order.getOrderMeta())||void 0===n?void 0:n.token;if(!d)throw new ot(tt.MissingOrder);return yield s.execute({methodId:r,payment:o,bigpayBaseUrl:i,token:d}),this._store.getState()})}finalize(e){return sg(this,void 0,void 0,function*(){const t=this._store.getState().order.getOrderOrThrow();if(t.isComplete)return this._store.getState();const{bigpayBaseUrl:n}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==e?void 0:e.methodId))throw new Vt('Unable to submit payment because "options.methodId" argument is not provided.');const i=this._store.getState().order.getPaymentId(e.methodId);if(!i||!t||this._completedPayments.isCompleted(i))throw new Ym;const{orderId:r}=t;return yield this._paymentResumer.resume({paymentId:i,bigpayBaseUrl:n,orderId:r}).catch(e=>{throw this._completedPayments.setCompleted(i),e}),this._store.getState()})}initialize(e){return sg(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new Vt('Unable to submit payment because "options.methodId" argument is not provided.');const t=((e,t)=>{const n=e.getState().paymentMethods.getPaymentMethod(t);if(n&&Hy(n))return n})(this._store,e.methodId);if(!t)throw new gn(ln.PaymentNotInitialized);if(this._subStrategy=this._subStrategyRegistry.getByMethod(t),!this._subStrategy)throw new gn(ln.PaymentNotInitialized);return yield this._subStrategy.initialize(e),this._store.getState()})}deinitialize(e){var t;return sg(this,void 0,void 0,function*(){return null===(t=this._subStrategy)||void 0===t||t.deinitialize(),this._store.getState()})}}!function(e){e.CARD="card_ui",e.NONE="none",e.UNSUPPORTED="unsupported"}(ag||(ag={}));const cg=x([[e=>"card_ui"===e.type,N(ag.CARD)],[e=>"none"===e.type,N(ag.NONE)],[ve,N(ag.UNSUPPORTED)]]);class lg extends Gt{getByMethod(e){const t=cg(e.initializationStrategy);return this.get(t)}}var ug=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hg{constructor(e,t,n,i){this._store=e,this._orderActionCreator=t,this._hostedFormFactory=n,this._ppsdkStepHandler=i}execute(e){return ug(this,void 0,void 0,function*(){const t=this._hostedForm;if(!t)throw new gn(ln.PaymentNotInitialized);const{additionalAction:n,payment:i}=e;if(!i||!i.methodId)throw new Yy(["payment.methodId"]);yield t.validate();const{payload:r}=yield t.submit(i,n),{response:o}=r;yield this._ppsdkStepHandler.handle(o,{continue:{humanVerification:t=>ug(this,void 0,void 0,function*(){return this.execute(Object.assign({additionalAction:t},e))})}}),yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder())})}initialize(e){return ug(this,void 0,void 0,function*(){const t=e&&e.creditCard&&e.creditCard.form,{config:n,checkout:i}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:r=""}={}}=n.getStoreConfig()||{},o=i.getCheckoutOrThrow().id;if(!t)throw new Vt;const a=t&&this._hostedFormFactory.create(r,t,o);yield a.attach(),this._hostedForm=a})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}class pg{constructor(e,t){this._requestSender=e,this._stepHandler=t}execute({methodId:e,bigpayBaseUrl:t,token:n}){const i={credentials:!1,body:{payment_method_id:e},headers:{authorization:n,"X-XSRF-TOKEN":null}};return this._requestSender.post(`${t}/payments`,i).then(e=>this._stepHandler.handle(e))}initialize(){return Promise.resolve()}deinitialize(){}}var mg,yg,gg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fg{constructor(e,t){this._requestSender=e,this._stepHandler=t}resume({paymentId:e,bigpayBaseUrl:t,orderId:n}){return gg(this,void 0,void 0,function*(){const i={credentials:!1,headers:{authorization:yield this._getToken(n).catch(()=>{throw new Ym}),"X-XSRF-TOKEN":null}};return this._requestSender.get(`${t}/payments/${e}`,i).then(e=>this._stepHandler.handle(e))})}_getToken(e){return gg(this,void 0,void 0,function*(){const t={params:{order_id:e}};return this._requestSender.get("/api/storefront/payments/auth-token",t).then(({body:e})=>e.auth_token)})}}class vg extends Jy{constructor(e,t,n,i,r){super(e,t,n,i),this._wepayRiskClient=r}initialize(e){return this._wepayRiskClient.initialize(),super.initialize(e)}execute(e,t){const n=this._wepayRiskClient.getRiskToken(),i=de({},e,{payment:{paymentData:{deviceSessionId:n}}});return super.execute(i,t)}}class _g{constructor(e){this._scriptLoader=e}initialize(){return this._scriptLoader.loadScript("//static.wepay.com/min/js/risk.1.latest.js").then(()=>this._riskClient=window.WePay.risk).then(()=>this)}getRiskToken(){if(!this._riskClient)throw new gn(ln.PaymentNotInitialized);return this._riskClient.generate_risk_token(),this._riskClient.get_risk_token()}}class Sg{constructor(e){this._requestSender=e}createBuyNowCart(e,{timeout:t}={}){const n=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post("/api/storefront/carts",{body:e,headers:n,timeout:t})}}!function(e){e.UpdatePaymentProviderCustomer="UPDATE_PAYMENT_PROVIDER_CUSTOMER"}(mg||(mg={}));class Ig{updatePaymentProviderCustomer(e){return C(l(mg.UpdatePaymentProviderCustomer,e))}}!function(e){e.ForgetCheckoutRemoteCustomerRequested="FORGET_CHECKOUT_REMOTE_CUSTOMER_REQUESTED",e.ForgetCheckoutRemoteCustomerSucceeded="FORGET_CHECKOUT_REMOTE_CUSTOMER_SUCCEEDED",e.ForgetCheckoutRemoteCustomerFailed="FORGET_CHECKOUT_REMOTE_CUSTOMER_FAILED",e.InitializeRemoteBillingRequested="INITIALIZE_REMOTE_BILLING_REQUESTED",e.InitializeRemoteBillingSucceeded="INITIALIZE_REMOTE_BILLING_SUCCEEDED",e.InitializeRemoteBillingFailed="INITIALIZE_REMOTE_BILLING_FAILED",e.InitializeRemoteShippingRequested="INITIALIZE_REMOTE_SHIPPING_REQUESTED",e.InitializeRemoteShippingSucceeded="INITIALIZE_REMOTE_SHIPPING_SUCCEEDED",e.InitializeRemoteShippingFailed="INITIALIZE_REMOTE_SHIPPING_FAILED",e.InitializeRemotePaymentRequested="INITIALIZE_REMOTE_PAYMENT_REQUESTED",e.InitializeRemotePaymentSucceeded="INITIALIZE_REMOTE_PAYMENT_SUCCEEDED",e.InitializeRemotePaymentFailed="INITIALIZE_REMOTE_PAYMENT_FAILED",e.LoadRemoteSettingsRequested="LOAD_REMOTE_SETTINGS_REQUESTED",e.LoadRemoteSettingsSucceeded="LOAD_REMOTE_SETTINGS_SUCCEEDED",e.LoadRemoteSettingsFailed="LOAD_REMOTE_SETTINGS_FAILED",e.SignOutRemoteCustomerRequested="SIGN_OUT_REMOTE_CUSTOMER_REQUESTED",e.SignOutRemoteCustomerSucceeded="SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED",e.SignOutRemoteCustomerFailed="SIGN_OUT_REMOTE_CUSTOMER_FAILED",e.UpdateRemoteCheckout="UPDATE_REMOTE_CHECKOUT"}(yg||(yg={}));var wg;class Cg{constructor(e,t){this._remoteCheckoutRequestSender=e,this._checkoutActionCreator=t}initializeBilling(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteBillingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeBilling(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteBillingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteBillingFailed,t,{methodId:e}))})})}initializeShipping(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteShippingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeShipping(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteShippingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteShippingFailed,t,{methodId:e}))})})}initializePayment(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemotePaymentRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializePayment(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemotePaymentSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemotePaymentFailed,t,{methodId:e}))})})}loadSettings(e,t){return m.create(n=>{n.next(l(yg.LoadRemoteSettingsRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.loadSettings(e,t).then(({body:t})=>{n.next(l(yg.LoadRemoteSettingsSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.LoadRemoteSettingsFailed,t,{methodId:e}))})})}signOut(e,t){return m.create(n=>{n.next(l(yg.SignOutRemoteCustomerRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.signOut(e,t).then(()=>{n.next(l(yg.SignOutRemoteCustomerSucceeded,void 0,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.SignOutRemoteCustomerFailed,t,{methodId:e}))})})}forgetCheckout(e,t){return g(C(l(yg.ForgetCheckoutRemoteCustomerRequested,void 0,{methodId:e})),f(()=>{return n=this,i=void 0,o=function*(){return yield this._remoteCheckoutRequestSender.forgetCheckout(t),yield this._checkoutActionCreator.loadCurrentCheckout(),l(yg.ForgetCheckoutRemoteCustomerSucceeded,void 0,{methodId:e})},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(t=>Ke(yg.ForgetCheckoutRemoteCustomerFailed,t,{methodId:e})))}updateCheckout(e,t){return l(yg.UpdateRemoteCheckout,t,{methodId:e})}}class bg{constructor(e){this._requestSender=e}initializeBilling(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/billing`;return this._requestSender.get(i,{params:t,timeout:n,headers:et})}initializeShipping(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/shipping`;return this._requestSender.get(i,{params:t,timeout:n,headers:et})}initializePayment(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/payment`;return this._requestSender.get(i,{params:t,timeout:n,headers:et})}loadSettings(e,{timeout:t}={}){const n=`/remote-checkout/${e}/settings`;return this._requestSender.get(n,{timeout:t,headers:et})}signOut(e,{timeout:t}={}){const n=`/remote-checkout/${e}/signout`;return this._requestSender.get(n,{timeout:t,headers:et})}generateToken({timeout:e}={}){return this._requestSender.get("/remote-checkout-token",{timeout:e,headers:et})}trackAuthorizationEvent({timeout:e}={}){return this._requestSender.post("/remote-checkout/events/shopper-checkout-service-provider-authorization-requested",{timeout:e,headers:et})}forgetCheckout({timeout:e}={}){return this._requestSender.post("/remote-checkout/forget-checkout",{timeout:e,headers:et})}}!function(e){e.CreateConsignmentsRequested="CREATE_CONSIGNMENTS_REQUESTED",e.CreateConsignmentsSucceeded="CREATE_CONSIGNMENTS_SUCCEEDED",e.CreateConsignmentsFailed="CREATE_CONSIGNMENTS_FAILED",e.UpdateConsignmentRequested="UPDATE_CONSIGNMENT_REQUESTED",e.UpdateConsignmentSucceeded="UPDATE_CONSIGNMENT_SUCCEEDED",e.UpdateConsignmentFailed="UPDATE_CONSIGNMENT_FAILED",e.DeleteConsignmentRequested="DELETE_CONSIGNMENT_REQUESTED",e.DeleteConsignmentSucceeded="DELETE_CONSIGNMENT_SUCCEEDED",e.DeleteConsignmentFailed="DELETE_CONSIGNMENT_FAILED",e.UpdateShippingOptionRequested="UPDATE_SHIPPING_OPTION_REQUESTED",e.UpdateShippingOptionSucceeded="UPDATE_SHIPPING_OPTION_SUCCEEDED",e.UpdateShippingOptionFailed="UPDATE_SHIPPING_OPTION_FAILED",e.LoadShippingOptionsRequested="LOAD_SHIPPING_OPTIONS_REQUESTED",e.LoadShippingOptionsSucceeded="LOAD_SHIPPING_OPTIONS_SUCCEEDED",e.LoadShippingOptionsFailed="LOAD_SHIPPING_OPTIONS_FAILED"}(wg||(wg={}));class Pg{constructor(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}unassignItemsByAddress(e,t){return n=>{const i=n.getState();if(!i.checkout.getCheckout())throw new ot(tt.MissingCheckout);const r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);if(!o)throw new Vt("No consignment found for the specified address");const a=this._removeLineItems(e.lineItems,o,i.cart.getCart());return a.length?this.updateConsignment({id:o.id,address:r,lineItems:a},t)(n):this.deleteConsignment(o.id,t)(n)}}assignItemsByAddress(e,t){return n=>{const i=n.getState(),r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);return this._createOrUpdateConsignment({id:o&&o.id,address:r,lineItems:this._addLineItems(e.lineItems,o,i.cart.getCart())},t)(n)}}selectShippingOption(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout(),a=r.consignments.getConsignments();if(!o)throw new ot(tt.MissingCheckout);if(!a||!a.length)throw new ot(tt.MissingConsignments);const s={id:a[0].id,shippingOptionId:e},d={id:a[0].id};i.next(l(wg.UpdateShippingOptionRequested,void 0,d)),this._consignmentRequestSender.updateConsignment(o.id,s,t).then(({body:e})=>{i.next(l(wg.UpdateShippingOptionSucceeded,e,d)),i.complete()}).catch(e=>{i.error(h(wg.UpdateShippingOptionFailed,e,d))})})}loadShippingOptions(e){return t=>m.create(n=>{const i=t.getState().checkout.getCheckout();if(!i)throw new ot(tt.MissingCheckout);n.next(l(wg.LoadShippingOptionsRequested)),this._checkoutRequestSender.loadCheckout(i.id,Object.assign(Object.assign({},e),{params:{include:[xt.AvailableShippingOptions]}})).then(({body:e})=>{n.next(l(wg.LoadShippingOptionsSucceeded,e)),n.complete()}).catch(e=>{n.error(h(wg.LoadShippingOptionsFailed,e))})})}updateAddress(e,t){return n=>{const i=this._getUpdateAddressRequestBody(e,n),r=n.getState().consignments.getConsignments();return r&&r.length&&(i.id=r[0].id),this._createOrUpdateConsignment(i,t)(n)}}createConsignments(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new ot(tt.MissingCheckout);i.next(l(wg.CreateConsignmentsRequested)),this._consignmentRequestSender.createConsignments(r.id,e,t).then(({body:e})=>{i.next(l(wg.CreateConsignmentsSucceeded,e)),i.complete()}).catch(e=>{i.error(h(wg.CreateConsignmentsFailed,e))})})}updateConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new ot(tt.MissingCheckout);const o={id:e.id};i.next(l(wg.UpdateConsignmentRequested,void 0,o)),this._consignmentRequestSender.updateConsignment(r.id,e,t).then(({body:e})=>{i.next(l(wg.UpdateConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(wg.UpdateConsignmentFailed,e,o))})})}deleteConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout(),o={id:e};if(!r||!r.id)throw new ot(tt.MissingCheckout);i.next(l(wg.DeleteConsignmentRequested,void 0,o)),this._consignmentRequestSender.deleteConsignment(r.id,e,t).then(({body:e})=>{i.next(l(wg.DeleteConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(wg.DeleteConsignmentFailed,e,o))})})}updateShippingOption(e,t){return n=>m.create(i=>{var r;const o=n.getState().checkout.getCheckout(),a=n.getState().consignments.getConsignmentById(e.id);if((null===(r=null==a?void 0:a.selectedShippingOption)||void 0===r?void 0:r.id)===e.shippingOptionId)return void i.complete();if(!o||!o.id)throw new ot(tt.MissingCheckout);const s={id:e.id};i.next(l(wg.UpdateShippingOptionRequested,void 0,s)),this._consignmentRequestSender.updateConsignment(o.id,e,t).then(({body:e})=>{i.next(l(wg.UpdateShippingOptionSucceeded,e,s)),i.complete()}).catch(e=>{i.error(h(wg.UpdateShippingOptionFailed,e,s))})})}_createOrUpdateConsignment(e,t){return n=>{const i=n.getState().checkout.getCheckout();if(!i||!i.id)throw new ot(tt.MissingCheckout);return this._isUpdateConsignmentRequest(e)?this.updateConsignment(e,t)(n):this.createConsignments([e],t)(n)}}_getUpdateAddressRequestBody(e,t){const n=t.getState().cart.getCart();if(!n)throw new ot(tt.MissingCart);const{physicalItems:i,customItems:r=[]}=n.lineItems;return{address:e,lineItems:[...i,...r].map(e=>({itemId:e.id,quantity:e.quantity}))}}_removeLineItems(e,t,n){if(!n)throw new ot(tt.MissingCart);return this._hydrateLineItems(t.lineItemIds,n).map(t=>{const n=j(e,e=>e.itemId===t.itemId);return Object.assign(Object.assign({},t),{quantity:n?t.quantity-n.quantity:t.quantity})}).filter(e=>e.quantity>0)}_addLineItems(e,t,n){if(!t)return e;if(!n)throw new ot(tt.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,n)).filter(e=>e.quantity>0)}_hydrateLineItems(e,t){return e.map(e=>{const n=j(t.lineItems.physicalItems,t=>t.id===e);return{itemId:e,quantity:n?n.quantity:0}})}_isUpdateConsignmentRequest(e){return!!e.id}_consignmentHasAddress(e){return"object"==typeof e&&"address"in e}}const Og=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"];class Eg{constructor(e){this._requestSender=e}createConsignments(e,t,{timeout:n,params:{include:i}={}}={}){const r=`/api/storefront/checkouts/${e}/consignments`,o=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(r,{body:t,params:{include:en(Og,i)},headers:o,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}updateConsignment(e,t,{timeout:n,params:{include:i}={}}={}){const{id:r}=t,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["id"]),a=`/api/storefront/checkouts/${e}/consignments/${r}`,s=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.put(a,{body:o,params:{include:en(Og,i)},headers:s,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}deleteConsignment(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/consignments/${t}`,r=Object.assign({Accept:lt.JsonV1},et),o=Lt(Og);return this._requestSender.delete(i,{params:{include:o},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}var Ag,Tg;!function(e){e.LoadShippingCountriesRequested="LOAD_SHIPPING_COUNTRIES_REQUESTED",e.LoadShippingCountriesSucceeded="LOAD_SHIPPING_COUNTRIES_SUCCEEDED",e.LoadShippingCountriesFailed="LOAD_SHIPPING_COUNTRIES_FAILED"}(Ag||(Ag={}));class kg{constructor(e,t){this._shippingCountryRequestSender=e,this._store=t}loadCountries(e){const{checkout:t}=this._store.getState(),n=t.getCheckout(),i=n?n.channelId:null;return m.create(t=>{t.next(l(Ag.LoadShippingCountriesRequested)),this._shippingCountryRequestSender.loadCountries(i,e).then(e=>{t.next(l(Ag.LoadShippingCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Ag.LoadShippingCountriesFailed,e))})})}}class Dg{constructor(e,t){this._requestSender=e,this._config=t}loadCountries(e,{timeout:t}={}){const n="/internalapi/v1/shipping/countries"+(e?`?channel_id=${e}`:""),i=Object.assign({"Accept-Language":this._config.locale},et);return this._requestSender.get(n,{headers:i,timeout:t})}}!function(e){e.ApplyStoreCreditRequested="APPLY_STORE_CREDIT_REQUESTED",e.ApplyStoreCreditSucceeded="APPLY_STORE_CREDIT_SUCCEEDED",e.ApplyStoreCreditFailed="APPLY_STORE_CREDIT_FAILED"}(Tg||(Tg={}));var Mg;class zg{constructor(e){this._storeCreditRequestSender=e}applyStoreCredit(e,t){return n=>g(C(l(Tg.ApplyStoreCreditRequested)),f(()=>{return i=this,r=void 0,a=function*(){var i;const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);const{id:o}=r,a=null!==(i=null==t?void 0:t.version)&&void 0!==i?i:r.version,{body:s}=yield e?this._storeCreditRequestSender.applyStoreCredit(o,Object.assign(Object.assign({},t),{version:a})):this._storeCreditRequestSender.removeStoreCredit(o,Object.assign(Object.assign({},t),{version:a}));return l(Tg.ApplyStoreCreditSucceeded,s)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>Ke(Tg.ApplyStoreCreditFailed,e)))}}class xg{constructor(e){this._requestSender=e}applyStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(i,{headers:r,timeout:t,params:{include:Lt(zt)},body:{version:n}})}removeStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.delete(i,{headers:r,timeout:t,params:{include:Lt(zt)},body:{version:n}})}}!function(e){e.UpdateSubscriptionsRequested="UPDATE_SUBSCRIPTIONS_REQUESTED",e.UpdateSubscriptionsSucceeded="UPDATE_SUBSCRIPTIONS_SUCCEEDED",e.UpdateSubscriptionsFailed="UPDATE_SUBSCRIPTIONS_FAILED"}(Mg||(Mg={}));class Ng extends Et{constructor(e){super(e),this.name="UpdateSubscriptionsError",this.type="update_subscriptions"}}class Rg{constructor(e){this._subscriptionsRequestSender=e}updateSubscriptions(e,t){return g(C(l(Mg.UpdateSubscriptionsRequested)),f(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._subscriptionsRequestSender.updateSubscriptions(e,t);return l(Mg.UpdateSubscriptionsSucceeded,n)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Ke(Mg.UpdateSubscriptionsFailed,new Ng(e))))}}class Fg{constructor(e){this._requestSender=e}updateSubscriptions(e,{timeout:t}={}){const n=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:n,timeout:t})}}function Lg(e){return Q(e)}const jg=se(e=>Array.isArray(e)?e.map(e=>Bg(e)):Lg(e)?Object.keys(e).reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:Bg(e[n])}),{}):e);jg.cache=new WeakMap;const Bg=e=>"object"==typeof e&&null!==e?jg(e):e;function Ug(e){return(...t)=>Bg(e(...t))}function qg({billingAddress:{getBillingAddress:e,getBillingAddressOrThrow:t},cart:{getCart:n,getCartOrThrow:i,getLocale:r},checkout:{getCheckout:o,getCheckoutOrThrow:a,getOutstandingBalance:s},config:{getContextConfig:d,getHost:c,getLocale:l,getStoreConfig:u,getStoreConfigOrThrow:h,getConfig:p},consignments:{getConsignments:m,getConsignmentsOrThrow:y},countries:{getCountries:g},customer:{getCustomer:f,getCustomerOrThrow:v},instruments:{getCardInstrument:_,getCardInstrumentOrThrow:S,getInstruments:I,getInstrumentsMeta:w},order:{getOrder:C,getOrderOrThrow:b,getOrderMeta:P},payment:{getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,isPaymentDataRequired:x},paymentMethods:{getPaymentMethod:N,getPaymentMethodOrThrow:R,getPaymentMethodsMeta:F},paymentProviderCustomer:{getPaymentProviderCustomer:L,getPaymentProviderCustomerOrThrow:j},paymentStrategies:{isInitialized:B},shippingAddress:{getShippingAddress:U,getShippingAddressOrThrow:q,getShippingAddresses:V,getShippingAddressesOrThrow:G},shippingCountries:{getShippingCountries:H}}){return{getHost:Ug(c),getLocale:Ug(l),getCartLocale:Ug(r),getBillingAddress:Ug(e),getBillingAddressOrThrow:Ug(t),getCart:Ug(n),getCartOrThrow:Ug(i),getCheckout:Ug(o),getCheckoutOrThrow:Ug(a),getCountries:Ug(g),getStoreConfig:Ug(u),getStoreConfigOrThrow:Ug(h),getConfig:Ug(p),getConsignments:Ug(m),getConsignmentsOrThrow:Ug(y),getContextConfig:Ug(d),getCustomer:Ug(f),getCustomerOrThrow:Ug(v),getCardInstrument:Ug(_),getInstruments:Ug(I),getCardInstrumentOrThrow:Ug(S),getOrder:Ug(C),getOrderOrThrow:Ug(b),getOrderMeta:Ug(P),getInstrumentsMeta:Ug(w),getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,getPaymentMethod:Ug(N),getPaymentMethodOrThrow:Ug(R),getPaymentMethodsMeta:Ug(F),getPaymentProviderCustomer:Ug(L),getPaymentProviderCustomerOrThrow:Ug(j),getShippingAddress:Ug(U),getShippingAddressOrThrow:Ug(q),getShippingAddresses:Ug(V),getShippingAddressesOrThrow:Ug(G),getShippingCountries:Ug(H),getOutstandingBalance:Ug(s),isPaymentDataRequired:x,isPaymentMethodInitialized:B}}var Vg,Gg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hg{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,f,v,_){this._store=e,this._storeProjectionFactory=t,this._checkoutActionCreator=n,this._checkoutValidator=i,this._hostedFormFactory=r,this._orderActionCreator=o,this._billingAddressActionCreator=a,this._consignmentActionCreator=s,this._paymentMethodActionCreator=d,this._paymentActionCreator=c,this._paymentHumanVerificationHandler=l,this._customerActionCreator=u,this._cartRequestSender=h,this._storeCreditActionCreator=p,this._couponActionCreator=m,this._spamProtectionActionCreator=y,this._paymentProviderCustomerActionCreator=g,this._shippingCountryActionCreator=f,this._remoteCheckoutActionCreator=v,this._paymentStrategyWidgetActionCreator=_,this._storeProjection=this._storeProjectionFactory.create(this._store)}createHostedForm(e,t){const n=this._storeProjection.getState().getCheckoutOrThrow().id;return this._hostedFormFactory.create(e,t,n)}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}getState(){return this._storeProjection.getState()}initializeOffsitePayment(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.initializeOffsitePayment(e)),this._storeProjection.getState()})}loadCheckout(e){return Gg(this,void 0,void 0,function*(){return e?yield this._store.dispatch(this._checkoutActionCreator.loadCheckout(e)):yield this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),this._storeProjection.getState()})}loadDefaultCheckout(){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()),this._storeProjection.getState()})}loadPaymentMethod(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e,t)),this._storeProjection.getState()})}loadPaymentMethods(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods(e)),this._storeProjection.getState()})}submitOrder(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.submitOrder(e,t)),this._storeProjection.getState()})}submitPayment(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.submitPayment(e)),this._storeProjection.getState()})}finalizeOrder(e){return Gg(this,void 0,void 0,function*(){const{order:{getOrderOrThrow:t}}=this._store.getState();return yield this._store.dispatch(this._orderActionCreator.finalizeOrder(t().orderId,e)),this._storeProjection.getState()})}updateBillingAddress(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(e)),this._storeProjection.getState()})}updateShippingAddress(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.updateAddress(e)),this._storeProjection.getState()})}selectShippingOption(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t)),this._storeProjection.getState()})}signInCustomer(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signInCustomer(e,t)),this._storeProjection.getState()})}signOutCustomer(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signOutCustomer(e)),this._storeProjection.getState()})}createBuyNowCart(e,t){return Gg(this,void 0,void 0,function*(){const{body:n}=yield this._cartRequestSender.createBuyNowCart(e,t);return n})}applyStoreCredit(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(e,t)),this._storeProjection.getState()})}applyCoupon(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.applyCoupon(e,t)),this._storeProjection.getState()})}removeCoupon(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.removeCoupon(e,t)),this._storeProjection.getState()})}verifyCheckoutSpamProtection(){return Gg(this,void 0,void 0,function*(){const{checkout:e}=this._store.getState(),{shouldExecuteSpamCheck:t}=e.getCheckoutOrThrow();return t&&(yield this._store.dispatch(this._spamProtectionActionCreator.verifyCheckoutSpamProtection())),this._storeProjection.getState()})}loadCurrentOrder(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder(e)),this._storeProjection.getState()})}updatePaymentProviderCustomer(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(e)),this._storeProjection.getState()})}loadShippingCountries(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._shippingCountryActionCreator.loadCountries(e)),this._storeProjection.getState()})}deleteConsignment(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.deleteConsignment(e,t)),this._storeProjection.getState()})}initializePayment(e,t,n){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(e,t,n)),this._storeProjection.getState()})}forgetCheckout(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.forgetCheckout(e,t)),this._storeProjection.getState()})}remoteCheckoutSignOut(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e,t)),this._storeProjection.getState()})}validateCheckout(e,t){return Gg(this,void 0,void 0,function*(){yield this._checkoutValidator.validate(e,t)})}handlePaymentHumanVerification(e,t){return Gg(this,void 0,void 0,function*(){return"string"==typeof e?this._paymentHumanVerificationHandler.handle(e,null!=t?t:""):this._paymentHumanVerificationHandler.handle(e)})}widgetInteraction(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentStrategyWidgetActionCreator.widgetInteraction(e),{queueId:"widgetInteraction"}),this._storeProjection.getState()})}}class Wg{constructor(e){this._transformSelectors=e}create(e){return yt(e,this._transformSelectors)}}function $g(e,t){const{config:{getHost:i,getLocale:r}}=e.getState();t||(t=n({host:i()}));const a=new Wg(qg),s=new rn(new tn(t),new Pt(new kt(t)),new an(new sn(t))),d=new ny(new tn(t)),c=new wy(e),l=new Vm(new Bm(t),new ny(new tn(t))),u=new dt(new ht(t),new Rg(new Fg(t))),h=new Pg(new Eg(t),new tn(t)),p=new Wm(new $m(t)),m=new Cy(new by(Gm(e)),l,new Gy,new cy(Sn(o()))),y=new cy(Sn(o())),g=new Jt(new Zt(t),s,new mn(Sn(o()),new In(t))),f=new zg(new xg(t)),v=new Mt(new jt(t)),_=Sn(o()),S=new In(t),I=new mn(_,S),w=new Sg(t),C=new Ig,b=new kg(new Dg(t,{locale:r()}),e),P=new Cg(new bg(t),s),O=new Qm;return new Hg(e,a,s,d,c,l,u,h,p,m,y,g,w,f,v,I,C,b,P,O)}!function(e){e.LoadInstrumentsRequested="LOAD_INSTRUMENTS_REQUESTED",e.LoadInstrumentsSucceeded="LOAD_INSTRUMENTS_SUCCEEDED",e.LoadInstrumentsFailed="LOAD_INSTRUMENTS_FAILED",e.DeleteInstrumentRequested="DELETE_INSTRUMENT_REQUESTED",e.DeleteInstrumentSucceeded="DELETE_INSTRUMENT_SUCCEEDED",e.DeleteInstrumentFailed="DELETE_INSTRUMENT_FAILED"}(Vg||(Vg={}));class Yg{constructor(e){this._instrumentRequestSender=e}loadInstruments(){return e=>m.create(t=>{t.next(l(Vg.LoadInstrumentsRequested));const n=this._getSessionContext(e),i=this._getCurrentAccessToken(e),r=this._getShippingAddress(e);return this._getValidAccessToken(i).then(e=>this._instrumentRequestSender.loadInstruments(Object.assign(Object.assign({},n),{authToken:e.vaultAccessToken}),r).then(({body:n})=>{t.next(l(Vg.LoadInstrumentsSucceeded,n,e)),t.complete()})).catch(e=>{t.error(h(Vg.LoadInstrumentsFailed,e))})})}deleteInstrument(e){return t=>m.create(n=>{n.next(l(Vg.DeleteInstrumentRequested,void 0,{instrumentId:e}));const i=this._getSessionContext(t),r=this._getCurrentAccessToken(t);return this._getValidAccessToken(r).then(t=>this._instrumentRequestSender.deleteInstrument(Object.assign(Object.assign({},i),{authToken:t.vaultAccessToken}),e).then(({body:i})=>{n.next(l(Vg.DeleteInstrumentSucceeded,i,Object.assign({instrumentId:e},t))),n.complete()})).catch(t=>{n.error(h(Vg.DeleteInstrumentFailed,t,{instrumentId:e}))})})}_isValidVaultAccessToken(e){if(!e||!e.vaultAccessToken)return!1;return function(e){const t=new Date(e.getTime());return t.setMinutes(e.getMinutes()+2),t}(new Date(e.vaultAccessExpiry)).valueOf()>Date.now()}_getCurrentAccessToken(e){const{instruments:t}=e.getState(),n=t.getInstrumentsMeta();if(n)return{vaultAccessToken:n.vaultAccessToken,vaultAccessExpiry:n.vaultAccessExpiry}}_getValidAccessToken(e){return e&&this._isValidVaultAccessToken(e)?Promise.resolve(e):this._instrumentRequestSender.getVaultAccessToken().then(({body:e})=>e)}_getShippingAddress(e){const t=e.getState(),n=t.shippingAddress.getShippingAddresses();return n.length>1?n:t.shippingAddress.getShippingAddress()}_getSessionContext(e){const t=e.getState(),n=t.config.getStoreConfig(),i=t.cart.getCart();if(!n)throw new ot(tt.MissingCheckoutConfig);if(!i)throw new ot(tt.MissingCart);const{customerId:r}=i,{storeId:o}=n.storeProfile,{code:a}=n.shopperCurrency.isTransactional?n.shopperCurrency:n.currency;return{customerId:r,storeId:o,currencyCode:a}}}var Kg,Jg,Zg=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n};class Qg{transformResponse(e){const t=this._transformResponse(e),{body:n}=t,i=Zg(t,["body"]);return Object.assign(Object.assign({},i),{body:{vaultedInstruments:this._transformVaultedInstruments(n.vaulted_instruments)}})}transformErrorResponse(e){return this._transformResponse(e)}transformVaultAccessResponse(e){return Object.assign(Object.assign({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}})}_transformVaultedInstruments(e=[]){return e.map(e=>this._isPayPalInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,externalId:e.external_id,trustedShippingAddress:e.trusted_shipping_address,method:"paypal",type:"account"}}(e):this._isBankInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,trustedShippingAddress:e.trusted_shipping_address,accountNumber:e.account_number,issuer:e.issuer,iban:e.iban,method:e.method,type:"bank"}}(e):function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,iin:e.iin,last4:e.last_4,expiryMonth:e.expiry_month,expiryYear:e.expiry_year,brand:e.brand,trustedShippingAddress:e.trusted_shipping_address,untrustedShippingCardVerificationMode:e.untrusted_shipping_address_card_verification_mode,method:e.method,type:"card"}}(e))}_isPayPalInstrument(e){return"paypal"===e.method_type}_isBankInstrument(e){return"bank"===e.method_type}_transformResponse(e){const{data:t}=e,n=Zg(e,["data"]);return Object.assign(Object.assign({},n),{body:t})}}class Xg{constructor(e,t){this._client=e,this._requestSender=t,this._transformer=new Qg}getVaultAccessToken({timeout:e}={}){return this._requestSender.get("/internalapi/v1/checkout/payments/vault-access-token",{timeout:e}).then(e=>Object.assign(Object.assign({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}}))}loadInstruments(e,t){return t?this._loadInstrumentsWithAddress(e,t):this._loadInstruments(e)}deleteInstrument(e,t){const n=Object.assign(Object.assign({},e),{instrumentId:t});return new Promise((e,t)=>{this._client.deleteShopperInstrument(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}_loadInstruments(e){return new Promise((t,n)=>{this._client.loadInstruments(e,(e,i)=>e?n(this._transformer.transformErrorResponse(e)):t(this._transformer.transformResponse(i)))})}_loadInstrumentsWithAddress(e,t){const n=Object.assign(Object.assign({},e),{shippingAddress:Array.isArray(t)?t.map(e=>Py(e)):Py(t)});return new Promise((e,t)=>{this._client.loadInstrumentsWithAddress(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}}!function(e){e.LoadPickupOptionsRequested="LOAD_PICKUP_OPTIONS_REQUESTED",e.LoadPickupOptionsSucceeded="LOAD_PICKUP_OPTIONS_SUCCEEDED",e.LoadPickupOptionsFailed="LOAD_PICKUP_OPTIONS_FAILED"}(Kg||(Kg={}));class ef{constructor(e){this._pickupOptionRequestSender=e}loadPickupOptions(e){return t=>new m(n=>{const i=this._hydrateApiQuery(t,e);n.next(l(Kg.LoadPickupOptionsRequested)),this._pickupOptionRequestSender.fetchPickupOptions(i).then(t=>{n.next(l(Kg.LoadPickupOptionsSucceeded,t.body.results,e)),n.complete()}).catch(e=>{n.error(h(Kg.LoadPickupOptionsFailed,e))})})}_hydrateApiQuery(e,t){const n=e.getState(),i=n.cart.getCartOrThrow();if(!i)throw new ot(tt.MissingCart);const r=n.consignments.getConsignmentById(t.consignmentId);if(!r)throw new ot(tt.MissingConsignments);const o=r.lineItemIds,a=i.lineItems.physicalItems.filter(e=>H(o,e.id)).map(e=>({variantId:e.variantId,quantity:e.quantity}));return{searchArea:t.searchArea,items:a}}}class tf{constructor(e){this._requestSender=e}fetchPickupOptions(e){return this._requestSender.post("/api/storefront/pickup-options",{headers:Object.assign({Accept:lt.Json},et),body:e})}}!function(e){e.UpdateAddressFailed="SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED",e.UpdateAddressRequested="SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED",e.UpdateAddressSucceeded="SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED",e.SelectOptionFailed="SHIPPING_STRATEGY_SELECT_OPTION_FAILED",e.SelectOptionRequested="SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED",e.SelectOptionSucceeded="SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED",e.InitializeFailed="SHIPPING_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="SHIPPING_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="SHIPPING_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED"}(Jg||(Jg={}));class nf{constructor(e){this._strategyRegistry=e}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Jg.UpdateAddressRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).updateAddress(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Jg.UpdateAddressSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Jg.UpdateAddressFailed,e,{methodId:o}))})})}selectOption(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Jg.SelectOptionRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).selectOption(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Jg.SelectOptionSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Jg.SelectOptionFailed,e,{methodId:o}))})})}initialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId,a=Object.assign(Object.assign({},e),{methodId:o});if(o&&i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Jg.InitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).initialize(a).then(()=>{n.next(l(Jg.InitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Jg.InitializeFailed,e,{methodId:o}))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId;if(o&&!i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Jg.DeinitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).deinitialize(Object.assign(Object.assign({},e),{methodId:o})).then(()=>{n.next(l(Jg.DeinitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Jg.DeinitializeFailed,e,{methodId:o}))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l(Jg.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l(Jg.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h(Jg.WidgetInteractionFailed,e,i))})})}}var rf,of=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class af{constructor(e,t,n,i,r){this._store=e,this._consignmentActionCreator=t,this._paymentMethodActionCreator=n,this._amazonPayV2PaymentProcessor=i,this._shippingStrategyActionCreator=r}updateAddress(e,t){const n=this._store.getState().shippingAddress.getShippingAddress();if(!n)throw new ot(tt.MissingShippingAddress);const i=Object.assign(Object.assign({},n),{customFields:e.customFields});return this._store.dispatch(this._consignmentActionCreator.updateAddress(i,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return of(this,void 0,void 0,function*(){const{amazonpay:t,methodId:n}=e;if(!t||!n)throw new Vt('Unable to proceed because "options.amazonpay" argument is not provided.');const i=(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))).paymentMethods.getPaymentMethodOrThrow(n);yield this._amazonPayV2PaymentProcessor.initialize(i);const{paymentToken:r,region:o}=i.initializationData,a=t.editAddressButtonId;if(r&&a){const e=this._shouldShowLoadingSpinner(o);this._bindEditButton(a,r,"changeAddress",e)}return this._store.getState()})}deinitialize(){return of(this,void 0,void 0,function*(){return yield this._amazonPayV2PaymentProcessor.deinitialize(),Promise.resolve(this._store.getState())})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>this._showLoadingSpinner())}this._amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_showLoadingSpinner(){return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction(()=>new Promise(w)),{queueId:"widgetInteraction"})}_shouldShowLoadingSpinner(e){return"us"!==e}}!function(e){e.CVV="cvv",e.PAN="pan"}(rf||(rf={}));var sf=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class df{constructor(e,t,n,i,r,o){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._braintreeIntegrationService=o}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){var t;return sf(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i,fastlane:r}=e||{},o=r||i,{onPayPalFastlaneAddressChange:a}=o||{};if(!n)throw new Vt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState();if(!s.customer.getCustomerOrThrow().isGuest)return Promise.resolve(this._store.getState());try{if(this._shouldRunAuthenticationFlow()){const e=s.paymentMethods.getPaymentMethod(n),{clientToken:i,isFastlaneStylingEnabled:r}=(null==e?void 0:e.initializationData)||{};i||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n)));const a=Ao(r?null===(t=null==e?void 0:e.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,null==o?void 0:o.styles);yield this._runAuthenticationFlowOrThrow(n,a)}"function"==typeof a&&(yield this._shouldUseBraintreeFastlaneShippingComponent(n))&&a(()=>this._handleBraintreeFastlaneShippingAddressChange())}catch(e){}return Promise.resolve(this._store.getState())})}_shouldRunAuthenticationFlow(){var e;const t=this._store.getState(),n=null===(e=t.cart.getCart())||void 0===e?void 0:e.id,i=Fr.get("bc-fastlane-sessionId")||"",r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=Nl(r)?r:{};return(null==o?void 0:o.authenticationState)!==Mi.CANCELED&&!(null==o?void 0:o.authenticationState)&&i===n}_runAuthenticationFlowOrThrow(e,t){var n,i;return sf(this,void 0,void 0,function*(){const r=this._store.getState(),o=r.cart.getCartOrThrow(),a=r.countries.getCountries()||[],s=r.paymentMethods.getPaymentMethodOrThrow(e),{clientToken:d,config:c}=s;if(!d)throw new ot(tt.MissingPaymentMethod);this._braintreeIntegrationService.initialize(d);const l=yield this._braintreeIntegrationService.getBraintreeFastlane(null==o?void 0:o.id,null==c?void 0:c.testMode,t),u=(null===(n=r.customer.getCustomer())||void 0===n?void 0:n.email)||(null===(i=r.billingAddress.getBillingAddress())||void 0===i?void 0:i.email);if(!u)return;const{lookupCustomerByEmail:h,triggerAuthenticationFlow:p}=l.identity,{customerContextId:m}=yield h(u);if(!m)return;const{authenticationState:y,profileData:g}=yield p(m);if(y===Mi.CANCELED)return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:[],instruments:[]})),void Fr.remove("bc-fastlane-sessionId");const f=this._getPayPalBillingAddress(g),v=g.shippingAddress,_=g.shippingAddress.phoneNumber,S=this._mapPayPalToBcAddress(v,a,_),I=this._mapPayPalToBcAddress(f,a,_);if(I&&S){const t=this._mergeShippingAndBillingAddresses(S,I),n=this._mapPayPalToBcInstrument(e,g.card),i=n?[n]:[];yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:t,instruments:i})),I&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},I),{id:String(I.id)})))),S&&o.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(S)))}})}_getPayPalBillingAddress(e){const{name:t,card:n}=e,i=n.paymentSource.card.billingAddress;return Object.assign(Object.assign({},i),{firstName:i.firstName||(null==t?void 0:t.firstName),lastName:i.lastName||(null==t?void 0:t.lastName)})}_getCountryNameByCountryCode(e,t){const n=t.find(t=>t.code===e);return(null==n?void 0:n.name)||""}_mapPayPalToBcAddress(e,t,n,i){return{id:Number(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:this._getCountryNameByCountryCode(e.countryCodeAlpha2,t),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:n||"",customFields:i||[]}}_normalizeAddress(e){return le(e,["id"])}_mergeShippingAndBillingAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))?[e]:[e,t]}_mapPayPalToBcInstrument(e,t){if(!t)return;const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:rf.CVV,type:"card"}}_handleBraintreeFastlaneShippingAddressChange(){var e;return sf(this,void 0,void 0,function*(){const t=this._store.getState().countries.getCountries()||[],n=yield this._braintreeIntegrationService.getBraintreeFastlane(),{selectionChanged:i,selectedAddress:r}=yield n.profile.showShippingAddressSelector();if(i){const n=this._store.getState(),i=n.shippingAddress.getShippingAddressesOrThrow(),o=n.paymentProviderCustomer.getPaymentProviderCustomer(),a=Nl(o)?o:{},s=this._mapPayPalToBcAddress(r,t,r.phoneNumber,null===(e=i[0])||void 0===e?void 0:e.customFields);if(s){const e=this._filterAddresses([s,...a.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},a),{addresses:e}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(s)),s}}})}_filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this._isEqualAddresses(e,t))?e:[...e,t]:e,[])}_isEqualAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))}_shouldUseBraintreeFastlaneShippingComponent(e){var t;return sf(this,void 0,void 0,function*(){const n=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomer(),i=Nl(n)?n:{};if(i&&i!==Mi.CANCELED){const n=yield this._getBraintreePaymentMethodOrThrow(e);return!!(null===(t=null==n?void 0:n.initializationData)||void 0===t?void 0:t.isFastlaneEnabled)}return!1})}_getBraintreePaymentMethodOrThrow(e){return sf(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}}class cf{constructor(e,t){this._store=e,this._consignmentActionCreator=t}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}var lf=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class uf{constructor(e,t,n,i,r,o,a){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._paypalSdkScriptLoader=o,this._paypalCommerceFastlaneUtils=a}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){return lf(this,void 0,void 0,function*(){const{methodId:t,paypalcommercefastlane:n,fastlane:i}=e||{},r=i||n,{onPayPalFastlaneAddressChange:o,styles:a}=r||{};if(!t)throw new Vt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState().customer.getCustomerOrThrow();if(!(null==s?void 0:s.isGuest))return Promise.resolve(this._store.getState());try{this._shouldAuthenticateUserWithFastlane()&&(yield this._initializePayPalSdk(t,a),yield this._authenticateUserWithFastlaneOtp(t)),"function"==typeof o&&this._shouldUsePayPalFastlaneShippingComponent()&&(yield this._initializePayPalSdk(t,a),o(()=>this._handlePayPalShippingAddressChange()))}catch(e){}return Promise.resolve(this._store.getState())})}_getPayPalPaymentMethodOrThrow(e){return lf(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}_getPayPalCustomerAuthenticationState(){const e=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomerOrThrow();var t;return((t=e)&&("authenticationState"in t||"addresses"in t||"instruments"in t)?e:{}).authenticationState}_shouldAuthenticateUserWithFastlane(){const e=this._store.getState().cart.getCartOrThrow(),t=this._paypalCommerceFastlaneUtils.getStorageSessionId();return!this._getPayPalCustomerAuthenticationState()&&t===e.id}_shouldUsePayPalFastlaneShippingComponent(){const e=this._getPayPalCustomerAuthenticationState();return!!e&&e!==vs.CANCELED}_initializePayPalSdk(e,t){var n;return lf(this,void 0,void 0,function*(){const i=this._store.getState().cart.getCartOrThrow(),r=yield this._getPayPalPaymentMethodOrThrow(e),{isDeveloperModeApplicable:o,isFastlaneStylingEnabled:a}=(null==r?void 0:r.initializationData)||{},s=!!o,d=rd(a?null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},t),c=yield this._paypalSdkScriptLoader.getPayPalFastlaneSdk(r,i.currency.code,i.id,i.locale);yield this._paypalCommerceFastlaneUtils.initializePayPalFastlane(c,s,d)})}_authenticateUserWithFastlaneOtp(e){var t,n;return lf(this,void 0,void 0,function*(){const i=this._store.getState(),r=i.cart.getCartOrThrow(),o=null===(t=i.customer.getCustomer())||void 0===t?void 0:t.email,a=null===(n=i.billingAddress.getBillingAddress())||void 0===n?void 0:n.email,s=o||a||"",{customerContextId:d}=yield this._paypalCommerceFastlaneUtils.lookupCustomerOrThrow(s),c=yield this._paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(d),{authenticationState:l,addresses:u,billingAddress:h,shippingAddress:p,instruments:m}=this._paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,c);yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:l,addresses:u,instruments:m})),c.authenticationState===vs.CANCELED?this._paypalCommerceFastlaneUtils.removeStorageSessionId():this._paypalCommerceFastlaneUtils.updateStorageSessionId(r.id),h&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},h),{id:String(h.id)})))),p&&r.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(p)))})}_handlePayPalShippingAddressChange(){var e;return lf(this,void 0,void 0,function*(){const t=this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:n,selectedAddress:i}=yield t.profile.showShippingAddressSelector();if(n){const t=this._store.getState(),n=t.shippingAddress.getShippingAddressesOrThrow(),r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=fp(r)?r:{},a=this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(i.address,i.name,i.phoneNumber,null===(e=n[0])||void 0===e?void 0:e.customFields),s=this._paypalCommerceFastlaneUtils.filterAddresses([a,...o.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},o),{addresses:s}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(a)),a}})}}var hf;class pf{constructor(e,t,n,i){this._store=e,this._stripeScriptLoader=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return t=this,n=void 0,r=function*(){if(!e.stripeupe)throw new Vt('Unable to proceed because "options" argument is not provided.');const{container:t,gatewayId:n,methodId:i,onChangeShipping:r,getStyles:o,availableCountries:a,getStripeState:s}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new Vt(`Unable to proceed because "${e}" argument is not provided.`)});const d=yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n,{params:{method:i}})),c=d.paymentMethods.getPaymentMethodOrThrow(i,n),{initializationData:l}=c;if(!c||!c.initializationData.stripePublishableKey||!c.clientToken)throw new ot(tt.MissingPaymentMethod);let u;this._stripeUPEClient=yield this._stripeScriptLoader.getStripeClient(l,d.cart.getLocale(),ka.V3,Fa,La);const h=o&&o(),{form:{getShippingAddressFields:p},shippingAddress:{getShippingAddress:m}}=this._store.getState(),y=p([],"");u=h?{variables:{colorPrimary:h.fieldInnerShadow,colorBackground:h.fieldBackground,colorText:h.labelText,colorDanger:h.fieldErrorText,colorTextSecondary:h.labelText,colorTextPlaceholder:h.fieldPlaceholderText,spacingUnit:"4px",borderRadius:"4px"},rules:{".Input":{borderColor:h.fieldBorder,color:h.fieldText,boxShadow:h.fieldInnerShadow}}}:{variables:{spacingUnit:"4px",borderRadius:"4px"}},this._stripeElements=yield this._stripeScriptLoader.getElements(this._stripeUPEClient,{clientSecret:c.clientToken,appearance:u});const g=m(),f=y.find(e=>"phone"===e.name);let v={mode:Ca.SHIPPING,allowedCountries:[a],fields:{phone:"always"},validation:{phone:{required:f&&f.required?"always":"never"}},display:{name:ba.SPLIT}};if(g){const{stateOrProvinceCode:e,countryCode:t,lastName:n,firstName:i,phone:r,address1:o,address2:a,city:d,postalCode:c}=g,l=e&&t?s(t,e):e;v=Object.assign(Object.assign({},v),{defaultValues:{firstName:i,lastName:n,phone:r,address:{line1:o,line2:a,city:d,state:l,postal_code:c,country:t}}})}let _=this._stripeElements.getElement(Da.SHIPPING);return _&&_.destroy(),_=this._stripeElements.create(Da.SHIPPING,v),_.on(za.CHANGE,e=>{if(!("isNewAddress"in e))throw new ot(tt.MissingShippingAddress);(e.complete||e.isNewAddress)&&(this.sendData&&clearTimeout(this.sendData),this.sendData=setTimeout(()=>{r(Object.assign(Object.assign({},e),{phoneFieldRequired:!!f&&f.required}))},1e3))}),_.mount(`#${t}`),Promise.resolve(this._store.getState())},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}deinitialize(){return Promise.resolve(this._store.getState())}}!function(e){e.SendSignInEmailRequested="SEND_SIGNIN_EMAIL_REQUESTED",e.SendSignInEmailSucceeded="SEND_SIGNIN_EMAIL_SUCCEEDED",e.SendSignInEmailFailed="SEND_SIGNIN_EMAIL_FAILED"}(hf||(hf={}));class mf{constructor(e){this._requestSender=e}sendSignInEmail(e,t){return g(C(l(hf.SendSignInEmailRequested)),f(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._requestSender.sendSignInEmail(e,t);return l(hf.SendSignInEmailSucceeded,n)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Ke(hf.SendSignInEmailFailed,e)))}}class yf{constructor(e){this._requestSender=e}sendSignInEmail({email:e,redirectUrl:t},{timeout:n}={}){const i=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post("/login.php?action=passwordless_login",{body:{email:e,redirect_url:t||Cn(window.top?window.top.location.href:"").pathname},headers:i,timeout:n})}}class gf{constructor(e){this._messageCustomizer=e}transform(e){var t;return e.message=(t=this._messageCustomizer(e))?t.split(/(?:\r\n|\n|\r)/).map(e=>e.replace(/^\s+/gm,"")).join(" ").trim():"",e}}let ff=class{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,f,v,_,S,I,w,C,b,P,O,E,A){this._store=e,this._storeProjection=t,this._extensionMessenger=n,this._extensionEventBroadcaster=i,this._b2bTokenActionCreator=r,this._billingAddressActionCreator=o,this._checkoutActionCreator=a,this._configActionCreator=s,this._customerActionCreator=d,this._consignmentActionCreator=c,this._countryActionCreator=l,this._couponActionCreator=u,this._customerStrategyActionCreator=h,this._errorActionCreator=p,this._giftCertificateActionCreator=m,this._instrumentActionCreator=y,this._orderActionCreator=g,this._paymentMethodActionCreator=f,this._paymentStrategyActionCreator=v,this._pickupOptionActionCreator=_,this._shippingCountryActionCreator=S,this._shippingStrategyActionCreator=I,this._signInEmailActionCreator=w,this._spamProtectionActionCreator=C,this._storeCreditActionCreator=b,this._subscriptionsActionCreator=P,this._formFieldsActionCreator=O,this._extensionActionCreator=E,this._workerExtensionMessenger=A,this._errorTransformer=function(e="development"===vt()){return new gf(t=>{if(!e||!function(e){return!(!e.subtype&&!e.type)}(t))return t.message;switch(t.subtype||t.type){case tt.MissingConsignments:return`\n ${t.message}\n The data could be unavailable because no shipping address has been provided.\n To fix this, create a consignment or update the shipping address before performing\n the same action again.\n `;case tt.MissingCart:case tt.MissingCheckout:return`\n ${t.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you can try calling \`CheckoutService#loadCheckout\`\n before performing the same action again.\n `;case tt.MissingCheckoutConfig:return`\n ${t.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you need to make sure \`CheckoutService\` is initialized\n properly by calling \`CheckoutService#loadCheckout\` before performing any\n other actions.\n `;case tt.MissingOrder:return`\n ${t.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you can try calling \`CheckoutService#loadOrder\`\n before performing the same action again.\n `;case tt.MissingOrderId:return`\n ${t.message}\n The data could be unavailable because no order has been created yet. You have\n to first create the order before you can perform the action.\n `;case tt.MissingPaymentMethod:return`\n ${t.message}\n The data could be unavailable because it has not loaded from the server, or\n configured by the merchant yet. To fix the former issue, you can try calling\n \`CheckoutService#loadPaymentMethods\` before performing the same action again.\n `;case ln.CustomerNotInitialized:return"\n In order to initialize the customer step of checkout, you need to call\n `CheckoutService#initializeCustomer`. Afterwards, you should be able to\n submit customer details.\n ";case ln.PaymentNotInitialized:return`\n ${t.message}\n In order to initialize the payment step of checkout, you need to call\n \`CheckoutService#initializePayment\`. Afterwards, you should be able to\n submit payment details.\n `;case ln.ShippingNotInitialized:return`\n ${t.message}\n In order to initialize the shipping step of checkout, you need to call\n \`CheckoutService#initializeShipping\`. Afterwards, you should be able to\n submit shipping details.\n `;default:return t.message}})}()}getState(){return this._storeProjection.getState()}notifyState(){this._storeProjection.notifyState()}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}hydrateInitialState(e){return this._dispatch(this._checkoutActionCreator.hydrateInitialState(e))}loadCheckout(e,t){return this._dispatch(e?this._checkoutActionCreator.loadCheckout(e,t):this._checkoutActionCreator.loadDefaultCheckout(t))}updateCheckout(e,t){const n=this._checkoutActionCreator.updateCheckout(e,t);return this._dispatch(n)}loadOrder(e,t){const n=this._orderActionCreator.loadOrder(e,t),i=this._formFieldsActionCreator.loadFormFields(t),r=this._configActionCreator.loadConfig(t);return Promise.all([this._dispatch(n),this._dispatch(r,{queueId:"config"}),this._dispatch(i,{queueId:"formFields"})]).then(()=>this.getState())}submitOrder(e,t){const n=this._paymentStrategyActionCreator.execute(e,t);return this._dispatch(n,{queueId:"paymentStrategy"})}finalizeOrderIfNeeded(e){const t=this._paymentStrategyActionCreator.finalize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadPaymentMethods(e){const t=this._paymentMethodActionCreator.loadPaymentMethods(e);return this._dispatch(t,{queueId:"paymentMethods"})}loadPaymentMethodByIds(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethodsById(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}loadPaymentMethod(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethod(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}initializePayment(e){const t=this._paymentStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}deinitializePayment(e){const t=this._paymentStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadBillingCountries(e){const t=this._countryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"billingCountries"})}loadShippingCountries(e){const t=this._shippingCountryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"shippingCountries"})}loadPickupOptions(e){const t=this._pickupOptionActionCreator.loadPickupOptions(e);return this._dispatch(t,{queueId:"pickupOptions"})}loadBillingAddressFields(e){return this.loadBillingCountries(e)}loadShippingAddressFields(e){return this.loadShippingCountries(e)}initializeCustomer(e){const t=this._customerStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}deinitializeCustomer(e){const t=this._customerStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}sendSignInEmail(e,t){const n=this._signInEmailActionCreator.sendSignInEmail(e,t);return this._dispatch(n,{queueId:"signInEmail"})}getB2BToken(e){const t=this._b2bTokenActionCreator.loadB2BToken(e);return this._dispatch(t,{queueId:"b2bToken"})}createCustomerAccount(e,t){const n=this._customerActionCreator.createCustomer(e,t);return this._dispatch(n)}createCustomerAddress(e,t){const n=this._customerActionCreator.createAddress(e,t);return this._dispatch(n)}updateSubscriptions(e,t){const n=this._subscriptionsActionCreator.updateSubscriptions(e,t);return this._dispatch(n,{queueId:"subscriptions"})}continueAsGuest(e,t){const n=this._billingAddressActionCreator.continueAsGuest(e,t);return this._dispatch(n)}signInCustomer(e,t){const n=this._customerStrategyActionCreator.signIn(e,t);return this._dispatch(n,{queueId:"customerStrategy"})}signOutCustomer(e){const t=this._customerStrategyActionCreator.signOut(e);return this._dispatch(t,{queueId:"customerStrategy"})}executePaymentMethodCheckout(e){const t=this._customerStrategyActionCreator.executePaymentMethodCheckout(e);return this._dispatch(t,{queueId:"customerStrategy"})}loadShippingOptions(e){const t=this._consignmentActionCreator.loadShippingOptions(e);return this._dispatch(t)}initializeShipping(e){const t=this._shippingStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}deinitializeShipping(e){const t=this._shippingStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}selectShippingOption(e,t){const n=this._shippingStrategyActionCreator.selectOption(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateShippingAddress(e,t){const n=this._shippingStrategyActionCreator.updateAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}createConsignments(e,t){const n=this._consignmentActionCreator.createConsignments(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}deleteConsignment(e,t){const n=this._consignmentActionCreator.deleteConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateConsignment(e,t){const n=this._consignmentActionCreator.updateConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}assignItemsToAddress(e,t){const n=this._consignmentActionCreator.assignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}unassignItemsToAddress(e,t){const n=this._consignmentActionCreator.unassignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}selectConsignmentShippingOption(e,t,n){const i=this._consignmentActionCreator.updateShippingOption({id:e,shippingOptionId:t},n);return this._dispatch(i,{queueId:"shippingStrategy"})}updateBillingAddress(e,t={}){const n=this._billingAddressActionCreator.updateAddress(e,t);return this._dispatch(n)}applyStoreCredit(e,t){const n=this._storeCreditActionCreator.applyStoreCredit(e,t);return this._dispatch(n)}applyCoupon(e,t){const n=this._couponActionCreator.applyCoupon(e,t);return this._dispatch(n)}removeCoupon(e,t){const n=this._couponActionCreator.removeCoupon(e,t);return this._dispatch(n)}applyGiftCertificate(e,t){const n=this._giftCertificateActionCreator.applyGiftCertificate(e,t);return this._dispatch(n)}removeGiftCertificate(e,t){const n=this._giftCertificateActionCreator.removeGiftCertificate(e,t);return this._dispatch(n)}loadInstruments(){const e=this._instrumentActionCreator.loadInstruments();return this._dispatch(e)}deleteInstrument(e){const t=this._instrumentActionCreator.deleteInstrument(e);return this._dispatch(t).then(()=>this.loadInstruments())}clearError(e){const t=this._errorActionCreator.clearError(e);return this._dispatch(t)}initializeSpamProtection(e){const t=this._spamProtectionActionCreator.initialize(e);return this._dispatch(t,{queueId:"spamProtection"})}executeSpamCheck(){const e=this._spamProtectionActionCreator.verifyCheckoutSpamProtection();return this._dispatch(e,{queueId:"spamProtection"})}loadExtensions(e){const t=this._extensionActionCreator.loadExtensions(e);return this._dispatch(t,{queueId:"extensions"})}renderExtension(e,t){return n=this,i=void 0,o=function*(){const n=this._extensionActionCreator.renderExtension(e,t,this._workerExtensionMessenger),i=yield this._dispatch(n,{queueId:"extensions"});return this._extensionEventBroadcaster.listen(),i},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}clearExtensionCache(e){this._extensionMessenger.clearCacheByRegion(e)}postMessageToExtension(e,t){this._extensionMessenger.post(e,t)}handleExtensionCommand(e,t,n){return this._extensionMessenger.listenForCommand(e,t,n)}handleExtensionQuery(e,t,n){return this._extensionMessenger.listenForQuery(e,t,n)}_dispatch(e,t){return this._store.dispatch(e,t).then(()=>this.getState()).catch(e=>{throw this._errorTransformer.transform(e)})}};ff=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],ff);const vf=ff;function _f(e){return(...t)=>{const n=t.pop();return e(...t,(...e)=>{const t=n(...e);return"function"==typeof t?Pe(t):t})}}const Sf=_f(Re),If=_f(Fe(Le,(e,t)=>je(e,t)));class wf extends Et{constructor(e,t){super(e,{message:t||"An unexpected error has occurred. The checkout process cannot continue as a result."}),this.name="UnrecoverableError",this.type="unrecoverable"}}function Cf(e){return e.reduce((e,t)=>t?[...e,t]:e,[]).join(" ")}class bf extends Et{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}class Pf{constructor(){this._factoryMethods={},this.register("default",(e,t)=>new Et(e,{message:t})),this.register("internal",(e,t)=>function(e,t){const{body:n}=e,{errors:i=[]}=n;return new Et(e,{message:Cf(i)||n.detail||n.title||t,errors:i.length?i.map(e=>({code:n.type,message:e})):[{code:n.type,message:n.detail||n.title}]})}(e,t)),this.register("storefront",(e,t)=>function(e,t){const{body:n}=e;return new Et(e,{message:t||n.detail||n.title,errors:[{code:n.code||n.type,message:n.detail||n.title}]})}(e,t)),this.register("payment",(e,t)=>ly(e,t)),this.register("timeout",e=>new bf(e))}register(e,t){this._factoryMethods[e]=t}createError(e,t){return(this._factoryMethods[this._getType(e)]||this._factoryMethods.default)(e,t)}_getType(e){if(0===e.status)return"timeout";if(this._isStorefrontErrorResponseBody(e.body))return"storefront";if(this._isInternalErrorResponseBody(e.body)){const t=re(e.body.type.split("/"));return t&&this._factoryMethods[t]?t:"internal"}const t=re(e.body&&e.body.errors);return t&&t.code&&this._factoryMethods[t.code]?t.code:"payment"}_isStorefrontErrorResponseBody(e){const t=e;return!this._isInternalErrorResponseBody(e)&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status&&"string"==typeof t.detail}_isInternalErrorResponseBody(e){const t=e;return"object"==typeof t.errors&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status}}function Of(e,t){return Array.isArray(e)?e.map(e=>Of(e,t)):Q(e)?_e(ue(e,t),(e,n,i)=>{e[i]=Of(n,t)},{}):e}function Ef(e,t){return function(e){return e.type===mt.ClearError}(t)?Of(e,e=>e===t.payload):e}function Af(e,t,n){return e===t||(e&&t&&"object"==typeof e&&"object"==typeof t?Array.isArray(e)&&Array.isArray(t)?function(e,t,n){if(e.length!==t.length)return!1;for(let i=0,r=e.length;i<r;i++)if(!Af(e[i],t[i],n))return!1;return!0}(e,t,n):!Array.isArray(e)&&!Array.isArray(t)&&(e instanceof Date&&t instanceof Date?function(e,t){return e.getTime()===t.getTime()}(e,t):!(e instanceof Date||t instanceof Date)&&(e instanceof RegExp&&t instanceof RegExp?function(e,t){return e.toString()===t.toString()}(e,t):!(e instanceof RegExp||t instanceof RegExp)&&function(e,t,n){const i=n&&n.keyFilter,r=i?Object.keys(e).filter(i):Object.keys(e),o=i?Object.keys(t).filter(i):Object.keys(t);if(r.length!==o.length)return!1;for(let i=0,o=r.length;i<o;i++){const o=r[i];if(!Object.prototype.hasOwnProperty.call(t,o))return!1;if(!Af(e[o],t[o],n))return!1}return!0}(e,t,n))):e===t)}function Tf(e,t,n){return e&&Object.prototype.hasOwnProperty.call(e,t)&&Af(e[t],n)?e:Object.assign(Object.assign({},e),{[t]:n})}const kf={errors:{},statuses:{}};function Df(e=kf,t){return d({data:Mf,errors:c(zf,Ef),statuses:xf})(e,t)}function Mf(e,t){return t.type===Je.LoadB2BTokenSucceeded?t.payload:e}function zf(e=kf.errors,t){switch(t.type){case Je.LoadB2BTokenRequested:case Je.LoadB2BTokenSucceeded:return Tf(e,"loadError",void 0);case Je.LoadB2BTokenFailed:return Tf(e,"loadError",t.payload);default:return e}}function xf(e=kf.statuses,t){switch(t.type){case Je.LoadB2BTokenRequested:return Tf(e,"isLoading",!0);case Je.LoadB2BTokenFailed:case Je.LoadB2BTokenSucceeded:return Tf(e,"isLoading",!1);default:return e}}function Nf(e,t){return void 0===t||Af(e,t)?e:t}const Rf={errors:{},statuses:{}};function Ff(e=Rf,t){return d({data:Lf,errors:c(jf,Ef),statuses:Bf})(e,t)}function Lf(e,t){var n,i;switch(t.type){case nt.UpdateBillingAddressSucceeded:case nt.ContinueAsGuestSucceeded:case Yt.LoadCheckoutSucceeded:return Nf(e,t.payload&&t.payload.billingAddress);case Kt.HydrateInitialState:return Nf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.billingAddress);default:return e}}function jf(e=Rf.errors,t){switch(t.type){case Yt.LoadCheckoutRequested:case Yt.LoadCheckoutSucceeded:return Tf(e,"loadError",void 0);case Yt.LoadCheckoutFailed:return Tf(e,"loadError",t.payload);case nt.UpdateBillingAddressRequested:case nt.UpdateBillingAddressSucceeded:return Tf(e,"updateError",void 0);case nt.UpdateBillingAddressFailed:return Tf(e,"updateError",t.payload);case Mg.UpdateSubscriptionsRequested:case Mg.UpdateSubscriptionsSucceeded:case nt.ContinueAsGuestRequested:case nt.ContinueAsGuestSucceeded:return Tf(e,"continueAsGuestError",void 0);case Mg.UpdateSubscriptionsFailed:case nt.ContinueAsGuestFailed:return Tf(e,"continueAsGuestError",t.payload);default:return e}}function Bf(e=Rf.statuses,t){switch(t.type){case Yt.LoadCheckoutRequested:return Tf(e,"isLoading",!0);case Yt.LoadCheckoutSucceeded:case Yt.LoadCheckoutFailed:return Tf(e,"isLoading",!1);case nt.UpdateBillingAddressRequested:return Tf(e,"isUpdating",!0);case nt.UpdateBillingAddressFailed:case nt.UpdateBillingAddressSucceeded:return Tf(e,"isUpdating",!1);case nt.ContinueAsGuestRequested:case Mg.UpdateSubscriptionsRequested:return Tf(e,"isContinuingAsGuest",!0);case Mg.UpdateSubscriptionsSucceeded:case Mg.UpdateSubscriptionsFailed:case nt.ContinueAsGuestFailed:case nt.ContinueAsGuestSucceeded:return Tf(e,"isContinuingAsGuest",!1);default:return e}}const Uf=function e(t,n,i){const{matchObject:r=(e,t)=>void 0!==e.id&&e.id===t.id}=i||{};if(!t)return n;if(!n||t===n)return t;let o=0,a=0;const s=(e,t,n)=>(o+=e===t?1:0,a+=e===n?1:0,e),d=n.map((n,i)=>{const o=t&&t[i];return Lg(o)&&Lg(n)?r(o,n)?s(qf(o,n),o,n):s(Nf(o,n),o,n):W(o)&&W(n)?s(e(o,n),o,n):s(Nf(o,n),o,n)});return o===n.length&&t&&t.length===n.length?t:a===n.length?n:d},qf=function e(t,n){return t?n&&t!==n?Object.keys(n).reduce((t,i)=>{const r=t[i],o=n[i];return Lg(r)&&Lg(o)?Tf(t,i,e(r,o)):W(r)&&W(o)?Tf(t,i,Uf(r,o)):Tf(t,i,o)},t):t:n},Vf={errors:{},statuses:{}};function Gf(e=Vf,t){return d({data:Hf,errors:c($f,Ef),statuses:Wf})(e,t)}function Hf(e,t){var n,i;switch(t.type){case nt.UpdateBillingAddressSucceeded:case Yt.LoadCheckoutSucceeded:case wg.CreateConsignmentsSucceeded:case wg.DeleteConsignmentSucceeded:case wg.UpdateConsignmentSucceeded:case wg.UpdateShippingOptionSucceeded:case wg.LoadShippingOptionsSucceeded:case Dt.ApplyCouponSucceeded:case Dt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return qf(e,t.payload&&t.payload.cart);case Kt.HydrateInitialState:return qf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.cart);default:return e}}function Wf(e=Vf.statuses,t){switch(t.type){case Yt.LoadCheckoutRequested:return Tf(e,"isLoading",!0);case Yt.LoadCheckoutFailed:case Yt.LoadCheckoutSucceeded:return Tf(e,"isLoading",!1);default:return e}}function $f(e=Vf.errors,t){switch(t.type){case Yt.LoadCheckoutRequested:case Yt.LoadCheckoutSucceeded:return Tf(e,"loadError",void 0);case Yt.LoadCheckoutFailed:return Tf(e,"loadError",t.payload);default:return e}}var Yf;!function(e){e.InitializeButtonFailed="INITIALIZE_BUTTON_FAILED",e.InitializeButtonRequested="INITIALIZE_BUTTON_REQUESTED",e.InitializeButtonSucceeded="INITIALIZE_BUTTON_SUCCEEDED",e.DeinitializeButtonFailed="DEINITIALIZE_BUTTON_FAILED",e.DeinitializeButtonRequested="DEINITIALIZE_BUTTON_REQUESTED",e.DeinitializeButtonSucceeded="DEINITIALIZE_BUTTON_SUCCEEDED"}(Yf||(Yf={}));const Kf={data:{},errors:{},statuses:{}},Jf={initializedContainers:{}},Zf={},Qf={};function Xf(e=Kf,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:ev}),errors:d({[t.meta.methodId]:tv}),statuses:d({[t.meta.methodId]:nv})})(e,t):e}function ev(e=Jf,t){switch(t.type){case Yf.InitializeButtonSucceeded:return t.meta&&t.meta.containerId?qf(e,{initializedContainers:{[t.meta.containerId]:!0}}):e;case Yf.DeinitializeButtonSucceeded:return Tf(e,"initializedContainers",{})}return e}function tv(e=Zf,t){switch(t.type){case Yf.InitializeButtonRequested:case Yf.InitializeButtonSucceeded:return Tf(e,"initializeError",void 0);case Yf.InitializeButtonFailed:return Tf(e,"initializeError",t.payload);case Yf.DeinitializeButtonRequested:case Yf.DeinitializeButtonSucceeded:return Tf(e,"deinitializeError",void 0);case Yf.DeinitializeButtonFailed:return Tf(e,"deinitializeError",t.payload);default:return e}}function nv(e=Qf,t){switch(t.type){case Yf.InitializeButtonRequested:return Tf(e,"isInitializing",!0);case Yf.InitializeButtonFailed:case Yf.InitializeButtonSucceeded:return Tf(e,"isInitializing",!1);case Yf.DeinitializeButtonRequested:return Tf(e,"isDeinitializing",!0);case Yf.DeinitializeButtonFailed:case Yf.DeinitializeButtonSucceeded:return Tf(e,"isDeinitializing",!1);default:return e}}const iv={meta:{},errors:{},statuses:{}};function rv(e=iv,t){return d({data:ov,errors:c(av,Ef),statuses:sv})(e,t)}function ov(e,t){var n;switch(t.type){case bt.LoadConfigSucceeded:return qf(e,t.payload);case Kt.HydrateInitialState:return qf(e,null===(n=t.payload)||void 0===n?void 0:n.config);default:return e}}function av(e=iv.errors,t){switch(t.type){case bt.LoadConfigSucceeded:return Tf(e,"loadError",void 0);case bt.LoadConfigFailed:return Tf(e,"loadError",t.payload);default:return e}}function sv(e=iv.statuses,t){switch(t.type){case bt.LoadConfigRequested:return Tf(e,"isLoading",!0);case bt.LoadConfigSucceeded:case bt.LoadConfigFailed:return Tf(e,"isLoading",!1);default:return e}}const dv={errors:{},statuses:{}};function cv(e=dv,t){return d({data:lv,errors:c(uv,Ef),statuses:hv})(e,t)}function lv(e,t){var n,i;switch(t.type){case Yt.LoadCheckoutSucceeded:case Dt.ApplyCouponSucceeded:case wg.UpdateShippingOptionSucceeded:case Dt.RemoveCouponSucceeded:case Mm.LoadOrderSucceeded:return Uf(e,t.payload&&t.payload.coupons);case Kt.HydrateInitialState:return Uf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.coupons);default:return e}}function uv(e={},t){switch(t.type){case Dt.ApplyCouponRequested:case Dt.ApplyCouponSucceeded:return Tf(e,"applyCouponError",void 0);case Dt.ApplyCouponFailed:return Tf(e,"applyCouponError",t.payload);case Dt.RemoveCouponRequested:case Dt.RemoveCouponSucceeded:return Tf(e,"removeCouponError",void 0);case Dt.RemoveCouponFailed:return Tf(e,"removeCouponError",t.payload);default:return e}}function hv(e={},t){switch(t.type){case Dt.ApplyCouponRequested:return Tf(e,"isApplyingCoupon",!0);case Dt.ApplyCouponSucceeded:case Dt.ApplyCouponFailed:return Tf(e,"isApplyingCoupon",!1);case Dt.RemoveCouponRequested:return Tf(e,"isRemovingCoupon",!0);case Dt.RemoveCouponSucceeded:case Dt.RemoveCouponFailed:return Tf(e,"isRemovingCoupon",!1);default:return e}}const pv={errors:{},statuses:{}};function mv(e=pv,t){return d({data:yv,errors:c(gv,Ef),statuses:fv})(e,t)}function yv(e,t){var n,i;switch(t.type){case Yt.LoadCheckoutSucceeded:case wg.CreateConsignmentsSucceeded:case wg.UpdateConsignmentSucceeded:case wg.DeleteConsignmentSucceeded:case wg.UpdateShippingOptionSucceeded:case Dt.ApplyCouponSucceeded:case Dt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return Uf(e,t.payload&&t.payload.giftCertificates);case Kt.HydrateInitialState:return Uf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.giftCertificates);default:return e}}function gv(e=pv.errors,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:case Nt.ApplyGiftCertificateSucceeded:return Tf(e,"applyGiftCertificateError",void 0);case Nt.ApplyGiftCertificateFailed:return Tf(e,"applyGiftCertificateError",t.payload);case Nt.RemoveGiftCertificateRequested:case Nt.RemoveGiftCertificateSucceeded:return Tf(e,"removeGiftCertificateError",void 0);case Nt.RemoveGiftCertificateFailed:return Tf(e,"removeGiftCertificateError",t.payload);default:return e}}function fv(e=pv.statuses,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:return Tf(e,"isApplyingGiftCertificate",!0);case Nt.ApplyGiftCertificateSucceeded:case Nt.ApplyGiftCertificateFailed:return Tf(e,"isApplyingGiftCertificate",!1);case Nt.RemoveGiftCertificateRequested:return Tf(e,"isRemovingGiftCertificate",!0);case Nt.RemoveGiftCertificateSucceeded:case Nt.RemoveGiftCertificateFailed:return Tf(e,"isRemovingGiftCertificate",!1);default:return e}}const vv={errors:{},statuses:{}};function _v(e=vv,t){return d({data:Sv,errors:c(Iv,Ef),statuses:wv})(e,t)}function Sv(e,t){var n,i;switch(t.type){case nt.ContinueAsGuestSucceeded:case Yt.LoadCheckoutSucceeded:return qf(e,t.payload&&t.payload.customer);case Ft.CreateCustomerAddressSucceeded:return qf(e,t.payload);case Kt.HydrateInitialState:return qf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.customer);default:return e}}function Iv(e=vv.errors,t){switch(t.type){case Ft.CreateCustomerRequested:case Ft.CreateCustomerSucceeded:return Tf(e,"createError",void 0);case Ft.CreateCustomerFailed:return Tf(e,"createError",t.payload);case Ft.CreateCustomerAddressRequested:case Ft.CreateCustomerAddressSucceeded:return Tf(e,"createAddressError",void 0);case Ft.CreateCustomerAddressFailed:return Tf(e,"createAddressError",t.payload);default:return e}}function wv(e=vv.statuses,t){switch(t.type){case Ft.CreateCustomerRequested:return Tf(e,"isCreating",!0);case Ft.CreateCustomerFailed:case Ft.CreateCustomerSucceeded:return Tf(e,"isCreating",!1);case Ft.CreateCustomerAddressRequested:return Tf(e,"isCreatingAddress",!0);case Ft.CreateCustomerAddressFailed:case Ft.CreateCustomerAddressSucceeded:return Tf(e,"isCreatingAddress",!1);default:return e}}const Cv={data:{},errors:{},statuses:{}};function bv(e=Cv,t){return d({data:Pv,errors:c(Ov,Ef),statuses:Ev})(e,t)}function Pv(e=Cv.data,t){switch(t.type){case $t.InitializeSucceeded:return qf(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case $t.DeinitializeSucceeded:return qf(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function Ov(e=Cv.errors,t){switch(t.type){case $t.InitializeRequested:case $t.InitializeSucceeded:return qf(e,{initializeErrors:Object.assign({},e.initializeErrors),initializeMethodId:e.initializeMethodId?e.initializeMethodId:void 0});case $t.InitializeFailed:return qf(e,{initializeErrors:Object.assign(Object.assign({},e.initializeErrors),{[t.meta&&t.meta.methodId]:t.payload}),initializeMethodId:t.meta&&t.meta.methodId});case $t.DeinitializeRequested:case $t.DeinitializeSucceeded:return qf(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case $t.DeinitializeFailed:return qf(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case $t.SignInRequested:case $t.SignInSucceeded:return qf(e,{signInError:void 0,signInMethodId:void 0});case $t.SignInFailed:return qf(e,{signInError:t.payload,signInMethodId:t.meta&&t.meta.methodId});case $t.SignOutRequested:case $t.SignOutSucceeded:return qf(e,{signOutError:void 0,signOutMethodId:void 0});case $t.SignOutFailed:return qf(e,{signOutError:t.payload,signOutMethodId:t.meta&&t.meta.methodId});case $t.ExecutePaymentMethodCheckoutRequested:case $t.ExecutePaymentMethodCheckoutSucceeded:return qf(e,{executePaymentMethodCheckoutError:void 0,executePaymentMethodCheckoutMethodId:void 0});case $t.ExecutePaymentMethodCheckoutFailed:return qf(e,{executePaymentMethodCheckoutError:t.payload,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case $t.WidgetInteractionStarted:case $t.WidgetInteractionFinished:return qf(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case $t.WidgetInteractionFailed:return qf(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function Ev(e=Cv.statuses,t){switch(t.type){case $t.InitializeRequested:return qf(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case $t.InitializeFailed:case $t.InitializeSucceeded:return qf(e,{isInitializing:!1,initializeMethodId:void 0});case $t.DeinitializeRequested:return qf(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case $t.DeinitializeFailed:case $t.DeinitializeSucceeded:return qf(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case $t.SignInRequested:return qf(e,{isSigningIn:!0,signInMethodId:t.meta&&t.meta.methodId});case $t.SignInFailed:case $t.SignInSucceeded:return qf(e,{isSigningIn:!1,signInMethodId:void 0});case $t.SignOutRequested:return qf(e,{isSigningOut:!0,signOutMethodId:t.meta&&t.meta.methodId});case $t.SignOutFailed:case $t.SignOutSucceeded:return qf(e,{isSigningOut:!1,signOutMethodId:void 0});case $t.ExecutePaymentMethodCheckoutRequested:return qf(e,{isExecutingPaymentMethodCheckout:!0,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case $t.ExecutePaymentMethodCheckoutFailed:case $t.ExecutePaymentMethodCheckoutSucceeded:return qf(e,{isExecutingPaymentMethodCheckout:!1,executePaymentMethodCheckoutMethodId:void 0});case $t.WidgetInteractionStarted:return qf(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case $t.WidgetInteractionFinished:case $t.WidgetInteractionFailed:return qf(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const Av={errors:{},statuses:{}};function Tv(e=Av,t){return d({data:kv,errors:c(Dv,Ef),statuses:Mv})(e,t)}function kv(e,t){var n;return t.type===un.LoadExtensionsSucceeded?Uf(e,t.payload):t.type===Kt.HydrateInitialState?Uf(e,null===(n=t.payload)||void 0===n?void 0:n.extensions):e}function Dv(e=Av.errors,t){switch(t.type){case un.LoadExtensionsRequested:case un.LoadExtensionsSucceeded:return Tf(e,"loadError",void 0);case un.RenderExtensionRequested:case un.RenderExtensionSucceeded:return Tf(e,"renderError",void 0);case un.LoadExtensionsFailed:return Tf(e,"loadError",t.payload);case un.RenderExtensionFailed:return Tf(e,"renderError",t.payload);default:return e}}function Mv(e=Av.statuses,t){switch(t.type){case un.LoadExtensionsRequested:return Tf(e,"isLoading",!0);case un.LoadExtensionsSucceeded:case un.LoadExtensionsFailed:return Tf(e,"isLoading",!1);default:return e}}const zv={errors:{},statuses:{}};function xv(e=zv,t){return d({data:Nv,extraFields:Rv,errors:c(Fv,Ef),statuses:Lv})(e,t)}function Nv(e,t){var n;switch(t.type){case nn.LoadFormFieldsSucceeded:return qf(e,t.payload);case Kt.HydrateInitialState:return qf(e,null===(n=t.payload)||void 0===n?void 0:n.formFields);default:return e}}function Rv(e,t){var n,i;return t.type===Kt.HydrateInitialState&&null!==(i=null===(n=t.payload)||void 0===n?void 0:n.extraFields)&&void 0!==i?i:e}function Fv(e=zv.errors,t){switch(t.type){case nn.LoadFormFieldsSucceeded:return Tf(e,"loadError",void 0);case nn.LoadFormFieldsFailed:return Tf(e,"loadError",t.payload);default:return e}}function Lv(e=zv.statuses,t){switch(t.type){case nn.LoadFormFieldsRequested:return Tf(e,"isLoading",!0);case nn.LoadFormFieldsSucceeded:case nn.LoadFormFieldsFailed:return Tf(e,"isLoading",!1);default:return e}}const jv={errors:{},statuses:{}};function Bv(e=jv,t){return d({data:Uv,errors:c(qv,Ef),statuses:Vv})(e,t)}function Uv(e,t){return t.type===Dm.LoadCountriesSucceeded?Uf(e,t.payload):e}function qv(e=jv.errors,t){switch(t.type){case Dm.LoadCountriesRequested:case Dm.LoadCountriesSucceeded:return Tf(e,"loadError",void 0);case Dm.LoadCountriesFailed:return Tf(e,"loadError",t.payload);default:return e}}function Vv(e=jv.statuses,t){switch(t.type){case Dm.LoadCountriesRequested:return Tf(e,"isLoading",!0);case Dm.LoadCountriesSucceeded:case Dm.LoadCountriesFailed:return Tf(e,"isLoading",!1);default:return e}}const Gv={errors:{},meta:{},statuses:{}};function Hv(e=Gv,t){return d({data:Wv,errors:c(Yv,Ef),meta:$v,statuses:Kv})(e,t)}function Wv(e,t){switch(t.type){case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:return qf(e,le(t.payload,["billingAddress","coupons"]));default:return e}}function $v(e,t){switch(t.type){case Mm.FinalizeOrderSucceeded:case Mm.SubmitOrderSucceeded:return qf(e,Object.assign(Object.assign({},t.meta),{callbackUrl:t.payload&&t.payload.order.callbackUrl,orderToken:t.payload&&t.payload.order.token,payment:t.payload&&t.payload.order&&t.payload.order.payment}));default:return e}}function Yv(e=Gv.errors,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsRequested:return Tf(e,"loadError",void 0);case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsFailed:return Tf(e,"loadError",t.payload);default:return e}}function Kv(e=Gv.statuses,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderPaymentsRequested:return Tf(e,"isLoading",!0);case Mm.LoadOrderSucceeded:case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsFailed:return Tf(e,"isLoading",!1);default:return e}}const Jv={};function Zv(e=Jv,t){return d({data:Qv})(e,t)}function Qv(e,t){switch(t.type){case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderSucceeded:return Nf(e,t.payload&&t.payload.billingAddress);default:return e}}function Xv(e={},t){return d({data:e_})(e,t)}function e_(e,t){return t.type===fy.SubmitPaymentSucceeded?t.payload:e}const t_={errors:{},statuses:{}};function n_(e=t_,t){return d({data:i_,errors:c(o_,Ef),meta:r_,statuses:a_})(e,t)}function i_(e,t){switch(t.type){case qm.LoadPaymentMethodSucceeded:return function(e,t,n){if(!t)return e;const i=pe(t,"id"),r="object"==typeof n?me(n):n||i,o=B(e,r),a=[...e];if(-1===o)a.push(t);else{const n=e[o];a[o]=Lg(n)&&Lg(t)?qf(n,t):t}return a}(e||[],t.payload,t.payload&&{id:t.payload.id,gateway:t.payload.gateway});case qm.LoadPaymentMethodsSucceeded:return Uf(e,t.payload,{matchObject:(e,t)=>e.id===t.id&&e.gateway===t.gateway});default:return e}}function r_(e,t){return t.type===qm.LoadPaymentMethodsSucceeded?qf(e,t.meta):e}function o_(e=t_.errors,t){switch(t.type){case qm.LoadPaymentMethodsRequested:case qm.LoadPaymentMethodsSucceeded:return Tf(e,"loadError",void 0);case qm.LoadPaymentMethodsFailed:return Tf(e,"loadError",t.payload);case qm.LoadPaymentMethodRequested:case qm.LoadPaymentMethodSucceeded:return qf(e,{loadMethodId:void 0,loadMethodError:void 0});case qm.LoadPaymentMethodFailed:return qf(e,{loadMethodId:t.meta.methodId,loadMethodError:t.payload});default:return e}}function a_(e=t_.statuses,t){switch(t.type){case qm.LoadPaymentMethodsRequested:return Tf(e,"isLoading",!0);case qm.LoadPaymentMethodsSucceeded:case qm.LoadPaymentMethodsFailed:return Tf(e,"isLoading",!1);case qm.LoadPaymentMethodRequested:return qf(e,{isLoadingMethod:!0,loadMethodId:t.meta.methodId});case qm.LoadPaymentMethodSucceeded:case qm.LoadPaymentMethodFailed:return qf(e,{isLoadingMethod:!1,loadMethodId:void 0});default:return e}}const s_={data:{},errors:{},statuses:{}};function d_(e=s_,t){return d({data:c_,errors:c(l_,Ef),statuses:u_})(e,t)}function c_(e=s_.data,t){switch(t.type){case Km.InitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return qf(e,{[r]:{isInitialized:!0}})}break;case Km.DeinitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return qf(e,{[r]:{isInitialized:!1}})}}return e}function l_(e=s_.errors,t){switch(t.type){case Km.InitializeRequested:case Km.InitializeSucceeded:return qf(e,{initializeError:void 0,initializeMethodId:void 0});case Km.InitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return qf(e,{initializeError:t.payload,initializeMethodId:n})}case Km.DeinitializeRequested:case Km.DeinitializeSucceeded:return qf(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Km.DeinitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return qf(e,{deinitializeError:t.payload,deinitializeMethodId:n})}case Km.ExecuteRequested:case Km.ExecuteSucceeded:return qf(e,{executeError:void 0,executeMethodId:void 0});case Km.ExecuteFailed:return qf(e,{executeError:t.payload,executeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeRequested:case Km.FinalizeSucceeded:return qf(e,{finalizeError:void 0,finalizeMethodId:void 0});case Km.FinalizeFailed:return qf(e,{finalizeError:t.payload,finalizeMethodId:t.meta&&t.meta.methodId});case Km.WidgetInteractionStarted:case Km.WidgetInteractionFinished:return qf(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Km.WidgetInteractionFailed:return qf(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function u_(e=s_.statuses,t){switch(t.type){case Km.InitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return qf(e,{isInitializing:!0,initializeMethodId:n})}case Km.InitializeFailed:case Km.InitializeSucceeded:return qf(e,{isInitializing:!1,initializeMethodId:void 0});case Km.DeinitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return qf(e,{isDeinitializing:!0,deinitializeMethodId:n})}case Km.DeinitializeFailed:case Km.DeinitializeSucceeded:return qf(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Km.ExecuteRequested:return qf(e,{isExecuting:!0,executeMethodId:t.meta&&t.meta.methodId});case Km.ExecuteFailed:case Km.ExecuteSucceeded:return qf(e,{isExecuting:!1,executeMethodId:void 0});case Km.FinalizeRequested:return qf(e,{isFinalizing:!0,finalizeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeFailed:case Km.FinalizeSucceeded:return qf(e,{isFinalizing:!1,finalizeMethodId:void 0});case Km.WidgetInteractionStarted:return qf(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Km.WidgetInteractionFinished:case Km.WidgetInteractionFailed:return qf(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const h_={data:{}};function p_(e=h_,t){return d({data:m_})(e,t)}function m_(e=h_.data,t){return t.type===mg.UpdatePaymentProviderCustomer?qf(e,t.payload):e}const y_={data:[],errors:{},statuses:{}};function g_(e=y_,t){return d({data:f_,errors:c(__,Ef),meta:v_,statuses:S_})(e,t)}function f_(e=y_.data,t){return t.type===Vg.LoadInstrumentsSucceeded?Uf(e,t.payload&&t.payload.vaultedInstruments||[]):e}function v_(e,t){switch(t.type){case Vg.LoadInstrumentsSucceeded:case Vg.DeleteInstrumentSucceeded:return qf(e,t.meta);default:return e}}function __(e=y_.errors,t){switch(t.type){case Vg.LoadInstrumentsRequested:case Vg.LoadInstrumentsSucceeded:return Tf(e,"loadError",void 0);case Vg.DeleteInstrumentRequested:case Vg.DeleteInstrumentSucceeded:return qf(e,{deleteError:void 0,failedInstrument:void 0});case Vg.LoadInstrumentsFailed:return Tf(e,"loadError",t.payload);case Vg.DeleteInstrumentFailed:return qf(e,{deleteError:t.payload,failedInstrument:t.meta.instrumentId});default:return e}}function S_(e=y_.statuses,t){switch(t.type){case Vg.LoadInstrumentsRequested:return Tf(e,"isLoading",!0);case Vg.DeleteInstrumentRequested:return qf(e,{isDeleting:!0,deletingInstrument:t.meta.instrumentId});case Vg.LoadInstrumentsSucceeded:case Vg.LoadInstrumentsFailed:return Tf(e,"isLoading",!1);case Vg.DeleteInstrumentSucceeded:case Vg.DeleteInstrumentFailed:return qf(e,{isDeleting:!1,deletingInstrument:void 0});default:return e}}const I_={data:{}};function w_(e=I_,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:C_})})(e,t):e}function C_(e,t){switch(t.type){case yg.InitializeRemoteBillingSucceeded:return Tf(e,"billing",t.payload&&t.payload.billing);case yg.InitializeRemoteShippingSucceeded:return Tf(e,"shipping",t.payload&&t.payload.shipping);case yg.LoadRemoteSettingsSucceeded:return Tf(e,"settings",t.payload);case yg.UpdateRemoteCheckout:return qf(e,t.payload);default:return e}}const b_={errors:{updateShippingOptionError:{},updateError:{},deleteError:{}},statuses:{isUpdating:{},isUpdatingShippingOption:{},isDeleting:{}}};function P_(e=b_,t){return d({data:O_,errors:c(E_,Ef),statuses:A_})(e,t)}function O_(e,t){var n,i;switch(t.type){case Yt.LoadCheckoutSucceeded:case wg.LoadShippingOptionsSucceeded:case wg.CreateConsignmentsSucceeded:case wg.UpdateConsignmentSucceeded:case wg.DeleteConsignmentSucceeded:case wg.UpdateShippingOptionSucceeded:case Dt.ApplyCouponSucceeded:case Dt.RemoveCouponSucceeded:return Uf(e,t.payload&&t.payload.consignments);case Ft.SignOutCustomerSucceeded:return Uf(e,[]);case Kt.HydrateInitialState:return Uf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.consignments);default:return e}}function E_(e=b_.errors,t){switch(t.type){case Yt.LoadCheckoutRequested:case Yt.LoadCheckoutSucceeded:case wg.LoadShippingOptionsSucceeded:case wg.LoadShippingOptionsRequested:return Tf(e,"loadError",void 0);case Yt.LoadCheckoutFailed:case wg.LoadShippingOptionsFailed:return Tf(e,"loadError",t.payload);case wg.CreateConsignmentsRequested:case wg.CreateConsignmentsSucceeded:return Tf(e,"createError",void 0);case wg.CreateConsignmentsFailed:return Tf(e,"createError",t.payload);case wg.UpdateConsignmentSucceeded:case wg.UpdateConsignmentRequested:return t.meta?qf(e,{updateError:{[t.meta.id]:void 0}}):e;case wg.UpdateConsignmentFailed:return t.meta?qf(e,{updateError:{[t.meta.id]:t.payload}}):e;case wg.DeleteConsignmentSucceeded:case wg.DeleteConsignmentRequested:return t.meta?qf(e,{deleteError:{[t.meta.id]:void 0}}):e;case wg.DeleteConsignmentFailed:return t.meta?qf(e,{deleteError:{[t.meta.id]:t.payload}}):e;case wg.UpdateShippingOptionRequested:case wg.UpdateShippingOptionSucceeded:return t.meta?qf(e,{updateShippingOptionError:{[t.meta.id]:void 0}}):e;case wg.UpdateShippingOptionFailed:return t.meta?qf(e,{updateShippingOptionError:{[t.meta.id]:t.payload}}):e;default:return e}}function A_(e=b_.statuses,t){switch(t.type){case Yt.LoadCheckoutRequested:return Tf(e,"isLoading",!0);case wg.LoadShippingOptionsRequested:return Tf(e,"isLoadingShippingOptions",!0);case Yt.LoadCheckoutSucceeded:case Yt.LoadCheckoutFailed:return Tf(e,"isLoading",!1);case wg.LoadShippingOptionsSucceeded:case wg.LoadShippingOptionsFailed:return Tf(e,"isLoadingShippingOptions",!1);case wg.CreateConsignmentsRequested:return Tf(e,"isCreating",!0);case wg.CreateConsignmentsSucceeded:case wg.CreateConsignmentsFailed:return Tf(e,"isCreating",!1);case wg.UpdateConsignmentRequested:return t.meta?qf(e,{isUpdating:{[t.meta.id]:!0}}):e;case wg.UpdateConsignmentSucceeded:case wg.UpdateConsignmentFailed:return t.meta?qf(e,{isUpdating:{[t.meta.id]:!1}}):e;case wg.DeleteConsignmentRequested:return t.meta?qf(e,{isDeleting:{[t.meta.id]:!0}}):e;case wg.DeleteConsignmentSucceeded:case wg.DeleteConsignmentFailed:return t.meta?qf(e,{isDeleting:{[t.meta.id]:!1}}):e;case wg.UpdateShippingOptionRequested:return t.meta?qf(e,{isUpdatingShippingOption:{[t.meta.id]:!0}}):e;case wg.UpdateShippingOptionSucceeded:case wg.UpdateShippingOptionFailed:return t.meta?qf(e,{isUpdatingShippingOption:{[t.meta.id]:!1}}):e;default:return e}}function T_(e,t){const n={};return Object.keys(e).forEach(i=>{const r=e[i],o=t?`${t}.${i}`:i;"object"==typeof r?Object.assign(n,T_(r,o)):n[o]=r}),n}function k_(e){return Object.keys(e).sort().reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]}),{})}const D_={errors:{},statuses:{}};function M_(e=D_,t){return d({data:z_,errors:c(x_,Ef),statuses:N_})(e,t)}function z_(e,t){if(t.type!==Kg.LoadPickupOptionsSucceeded)return e;if(t.meta){const n=k_(T_({consignmentId:t.meta.consignmentId,searchArea:t.meta.searchArea}));return Tf(e,btoa(`${JSON.stringify(n)}`),t.payload)}}function x_(e=D_.errors,t){switch(t.type){case Kg.LoadPickupOptionsRequested:case Kg.LoadPickupOptionsSucceeded:return Tf(e,"loadError",void 0);case Kg.LoadPickupOptionsFailed:return Tf(e,"loadError",t.payload);default:return e}}function N_(e=D_.statuses,t){switch(t.type){case Kg.LoadPickupOptionsRequested:return Tf(e,"isLoading",!0);case Kg.LoadPickupOptionsSucceeded:case Kg.LoadPickupOptionsFailed:return Tf(e,"isLoading",!1);default:return e}}const R_={errors:{},statuses:{}};function F_(e=R_,t){return d({data:L_,errors:c(j_,Ef),statuses:B_})(e,t)}function L_(e,t){return t.type===Ag.LoadShippingCountriesSucceeded?Uf(e,t.payload):e}function j_(e=R_.errors,t){switch(t.type){case Ag.LoadShippingCountriesRequested:case Ag.LoadShippingCountriesSucceeded:return Tf(e,"loadError",void 0);case Ag.LoadShippingCountriesFailed:return Tf(e,"loadError",t.payload);default:return e}}function B_(e=R_.statuses,t){switch(t.type){case Ag.LoadShippingCountriesRequested:return Tf(e,"isLoading",!0);case Ag.LoadShippingCountriesSucceeded:case Ag.LoadShippingCountriesFailed:return Tf(e,"isLoading",!1);default:return e}}const U_={data:{},errors:{},statuses:{}};function q_(e=U_,t){return d({data:V_,errors:c(G_,Ef),statuses:H_})(e,t)}function V_(e=U_.data,t){switch(t.type){case Jg.InitializeSucceeded:return qf(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Jg.DeinitializeSucceeded:return qf(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function G_(e=U_.errors,t){switch(t.type){case Jg.InitializeRequested:case Jg.InitializeSucceeded:return qf(e,{initializeError:void 0,initializeMethodId:void 0});case Jg.InitializeFailed:return qf(e,{initializeError:t.payload,initializeMethodId:t.meta&&t.meta.methodId});case Jg.DeinitializeRequested:case Jg.DeinitializeSucceeded:return qf(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Jg.DeinitializeFailed:return qf(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Jg.UpdateAddressRequested:case Jg.UpdateAddressSucceeded:return qf(e,{updateAddressError:void 0,updateAddressMethodId:void 0});case Jg.UpdateAddressFailed:return qf(e,{updateAddressError:t.payload,updateAddressMethodId:t.meta&&t.meta.methodId});case Jg.SelectOptionRequested:case Jg.SelectOptionSucceeded:return qf(e,{selectOptionError:void 0,selectOptionMethodId:void 0});case Jg.SelectOptionFailed:return qf(e,{selectOptionError:t.payload,selectOptionMethodId:t.meta&&t.meta.methodId});case Jg.WidgetInteractionStarted:case Jg.WidgetInteractionFinished:return qf(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Jg.WidgetInteractionFailed:return qf(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta&&t.meta.methodId});default:return e}}function H_(e=U_.statuses,t){switch(t.type){case Jg.InitializeRequested:return qf(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Jg.InitializeFailed:case Jg.InitializeSucceeded:return qf(e,{isInitializing:!1,initializeMethodId:void 0});case Jg.DeinitializeRequested:return qf(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Jg.DeinitializeFailed:case Jg.DeinitializeSucceeded:return qf(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Jg.UpdateAddressRequested:return qf(e,{isUpdatingAddress:!0,updateAddressMethodId:t.meta&&t.meta.methodId});case Jg.UpdateAddressFailed:case Jg.UpdateAddressSucceeded:return qf(e,{isUpdatingAddress:!1,updateAddressMethodId:void 0});case Jg.SelectOptionRequested:return qf(e,{isSelectingOption:!0,selectOptionMethodId:t.meta&&t.meta.methodId});case Jg.SelectOptionFailed:case Jg.SelectOptionSucceeded:return qf(e,{isSelectingOption:!1,selectOptionMethodId:void 0});case Jg.WidgetInteractionStarted:return qf(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta&&t.meta.methodId});case Jg.WidgetInteractionFinished:case Jg.WidgetInteractionFailed:return qf(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const W_={errors:{},statuses:{}};function $_(e=W_,t){return d({data:Y_,errors:c(K_,Ef),statuses:J_})(e,t)}function Y_(e,t){return t.type===hf.SendSignInEmailSucceeded?qf(e,t.payload):e}function K_(e=W_.errors,t){switch(t.type){case hf.SendSignInEmailRequested:case hf.SendSignInEmailSucceeded:return Tf(e,"sendError",void 0);case hf.SendSignInEmailFailed:return Tf(e,"sendError",t.payload);default:return e}}function J_(e=W_.statuses,t){switch(t.type){case hf.SendSignInEmailRequested:return Tf(e,"isSending",!0);case hf.SendSignInEmailFailed:case hf.SendSignInEmailSucceeded:return Tf(e,"isSending",!1);default:return e}}const Z_={errors:{},statuses:{}};function Q_(e=Z_,t){return d({errors:c(X_,Ef),statuses:eS})(e,t)}function X_(e=Z_.errors,t){switch(t.type){case Tg.ApplyStoreCreditRequested:case Tg.ApplyStoreCreditSucceeded:return Tf(e,"applyError",void 0);case Tg.ApplyStoreCreditFailed:return Tf(e,"applyError",t.payload);default:return e}}function eS(e=Z_.statuses,t){switch(t.type){case Tg.ApplyStoreCreditRequested:return Tf(e,"isApplying",!0);case Tg.ApplyStoreCreditSucceeded:case Tg.ApplyStoreCreditFailed:return Tf(e,"isApplying",!1);default:return e}}const tS={errors:{},statuses:{}};function nS(e=tS,t){return d({errors:c(iS,Ef),statuses:rS})(e,t)}function iS(e=tS.errors,t){switch(t.type){case Mg.UpdateSubscriptionsRequested:case Mg.UpdateSubscriptionsSucceeded:return Tf(e,"updateError",void 0);case Mg.UpdateSubscriptionsFailed:return Tf(e,"updateError",t.payload);default:return e}}function rS(e=tS.statuses,t){switch(t.type){case Mg.UpdateSubscriptionsRequested:return Tf(e,"isUpdating",!0);case Mg.UpdateSubscriptionsFailed:case Mg.UpdateSubscriptionsSucceeded:return Tf(e,"isUpdating",!1);default:return e}}const oS={errors:{},statuses:{}};function aS(e=oS,t){return d({data:sS,errors:c(dS,Ef),statuses:cS})(e,t)}function sS(e,t){var n;switch(t.type){case Yt.LoadCheckoutSucceeded:case Yt.UpdateCheckoutSucceeded:case Tg.ApplyStoreCreditSucceeded:case nt.UpdateBillingAddressSucceeded:case Dt.ApplyCouponSucceeded:case Dt.RemoveCouponSucceeded:case wg.CreateConsignmentsSucceeded:case wg.UpdateConsignmentSucceeded:case wg.DeleteConsignmentSucceeded:case wg.UpdateShippingOptionSucceeded:case wg.LoadShippingOptionsSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:case on.VerifyCheckoutSucceeded:return qf(e,le(t.payload,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));case Mm.SubmitOrderSucceeded:return Tf(e,"orderId",t.payload&&t.payload.order.orderId);case Kt.HydrateInitialState:return qf(e,le(null===(n=t.payload)||void 0===n?void 0:n.checkout,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));default:return e}}function dS(e=oS.errors,t){switch(t.type){case Yt.LoadCheckoutRequested:case Yt.LoadCheckoutSucceeded:return Tf(e,"loadError",void 0);case Yt.LoadCheckoutFailed:return Tf(e,"loadError",t.payload);case Yt.UpdateCheckoutRequested:case Yt.UpdateCheckoutSucceeded:return Tf(e,"updateError",void 0);case Yt.UpdateCheckoutFailed:return Tf(e,"updateError",t.payload);default:return e}}function cS(e=oS.statuses,t){switch(t.type){case Yt.LoadCheckoutRequested:return Tf(e,"isLoading",!0);case Yt.LoadCheckoutFailed:case Yt.LoadCheckoutSucceeded:return Tf(e,"isLoading",!1);case Yt.UpdateCheckoutRequested:return Tf(e,"isUpdating",!0);case Yt.UpdateCheckoutFailed:case Yt.UpdateCheckoutSucceeded:return Tf(e,"isUpdating",!1);case on.ExecuteRequested:return Tf(e,"isExecutingSpamCheck",!0);case on.ExecuteFailed:case on.ExecuteSucceeded:return Tf(e,"isExecutingSpamCheck",!1);default:return e}}function lS(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}function uS(e){return function(e){const t=Object.create(e);return function(e,t){let n=Object.getPrototypeOf(e);for(;n;)t(n),n=Object.getPrototypeOf(n)}(e,n=>{Object.getOwnPropertyNames(n).forEach(n=>{"constructor"!==n&&"function"==typeof t[n]&&"_"!==n.charAt(0)&&(t[n]=((e,t)=>(...n)=>p(e[t].call(e,...n)))(e,n))})}),t}(e)}const hS={"mollie.credit_card":{provider:"mollie",method:"credit_card"},"adyenv2.scheme":{provider:"adyenv2",method:"scheme"},"adyenv3.scheme":{provider:"adyenv3",method:"scheme"},"adyenv2.bcmc":{provider:"adyenv2",method:"bcmc"},"adyenv2.ideal":{provider:"adyenv2",method:"ideal"},"adyenv2.sepadirectdebit":{provider:"adyenv2",method:"sepadirectdebit"},"adyenv2.directEbanking":{provider:"adyenv2",method:"directEbanking"},"adyenv2.giropay":{provider:"adyenv2",method:"giropay"},braintree:{provider:"braintree",method:"credit_card"},braintreepaypal:{provider:"braintree",method:"paypal"},braintreeach:{provider:"braintree",method:"ach"},authorizenet:{provider:"authorizenet",method:"credit_card"},elavon:{provider:"elavon",method:"credit_card"},checkoutcom:{provider:"checkoutcom",method:"credit_card"},"checkoutcom.credit_card":{provider:"checkoutcom",method:"credit_card"},"checkoutcom.card":{provider:"checkoutcom",method:"card"},sagepay:{provider:"sagepay",method:"credit_card"},stripe:{provider:"stripe",method:"credit_card"},"stripev3.card":{provider:"stripev3",method:"card"},"stripeupe.card":{provider:"stripeupe",method:"card"},cybersource:{provider:"cybersource",method:"credit_card"},cybersourcev2:{provider:"cybersourcev2",method:"credit_card"},bnz:{provider:"bnz",method:"credit_card"},converge:{provider:"converge",method:"credit_card"},bluesnapv2:{provider:"bluesnapv2",method:"credit_card"},"bluesnapdirect.credit_card":{provider:"bluesnapdirect",method:"credit_card"},"bluesnapdirect.ecp":{provider:"bluesnapdirect",method:"ecp"},"bluesnapdirect.sepa_direct_debit":{provider:"bluesnapdirect",method:"sepa_direct_debit"},orbital:{provider:"orbital",method:"credit_card"},paymetric:{provider:"paymetric",method:"credit_card"},bolt:{provider:"bolt",method:"credit_card"},"barclaycard.credit_card":{provider:"barclaycard",method:"credit_card"},moneris:{provider:"moneris",method:"credit_card"},cba_mpgs:{provider:"cba_mpgs",method:"credit_card"},worldpayaccess:{provider:"worldpayaccess",method:"credit_card"},"worldpayaccess.credit_card":{provider:"worldpayaccess",method:"credit_card"},squarev2:{provider:"squarev2",method:"credit_card"},paypalcommercecreditcards:{provider:"paypalcommerce",method:"credit_card"},paypalcommerce:{provider:"paypalcommerce",method:"paypal"},bigcommerce_payments_creditcards:{provider:"bigcommerce_payments",method:"credit_card"},bigcommerce_payments:{provider:"bigcommerce_payments",method:"paypal"},tdonlinemart:{provider:"tdonlinemart",method:"credit_card"}};function pS(e){return me({firstName:e.firstName,lastName:e.lastName,company:e.company,address1:e.address1,address2:e.address2,city:e.city,stateOrProvince:e.stateOrProvince,countryCode:e.countryCode,postalCode:e.postalCode,phone:e.phone,customFields:e.customFields},G)}const mS={errors:{},statuses:{}};function yS(){const e=function(){const e=Sf(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.token},e=>()=>e),t=Sf(e=>e.errors.loadError,e=>()=>e),n=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=kf)=>({getToken:e(i),getLoadError:t(i),isLoading:n(i)}))}(),t=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingBillingAddress))),n=Sf(e=>e.errors.updateError,e=>()=>e),i=Sf(e=>e.errors.continueAsGuestError,e=>()=>e),r=Sf(e=>e.errors.loadError,e=>()=>e),o=Sf(e=>!!e.statuses.isUpdating,e=>()=>e),a=Sf(e=>!!e.statuses.isContinuingAsGuest,e=>()=>e),s=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((d=Rf)=>({getBillingAddress:e(d),getBillingAddressOrThrow:t(d),getUpdateError:n(d),getContinueAsGuestError:i(d),getLoadError:r(d),isUpdating:o(d),isContinuingAsGuest:a(d),isLoading:s(d)}))}(),n=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingCart))),n=Sf(e=>e.errors.loadError,e=>()=>e),i=Sf(e=>!!e.statuses.isLoading,e=>()=>e),r=Sf(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.locale},e=>()=>e);return Oe((o=Vf)=>({getCart:e(o),getCartOrThrow:t(o),getLoadError:n(o),isLoading:i(o),getLocale:r(o)}))}(),i=function(){const e=Sf(e=>e,e=>()=>e),t=Sf(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isInitializing)}return fe(e,{isInitializing:!0})})),n=Sf(e=>e.data,e=>Pe((t,n)=>{const i=e[t];return!!i&&(n?!0===i.initializedContainers[n]:fe(i.initializedContainers,e=>!0===e))})),i=Sf(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isDeinitializing)}return fe(e,{isDeinitializing:!0})})),r=Sf(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:j(Ce(e),e=>!(!e||!e.initializeError));return n&&n.initializeError})),o=Sf(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:j(Ce(e),e=>!(!e||!e.deinitializeError));return n&&n.deinitializeError}));return Oe((a=Kf)=>({getState:e(a),isInitializing:t(a),isInitialized:n(a),isDeinitializing:i(a),getInitializeError:r(a),getDeinitializeError:o(a)}))}(),r=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.data,e=>t=>{if(!e)return;const{flashMessages:n}=e.context;return n?void 0!==t?n.filter(({type:e})=>t===e):n:void 0}),n=Sf(e=>e.data,(e,{formState:t})=>t&&t.data,(e,t={customerAccount:[],shippingAddress:[],billingAddress:[]})=>()=>e?Object.assign(Object.assign({},e.storeConfig),{formFields:t}):void 0),i=Sf(n,e=>()=>lS(e(),()=>new ot(tt.MissingCheckoutConfig))),r=Sf(e=>e.data&&e.data.context,e=>()=>e),o=Sf(e=>e.meta&&e.meta.externalSource,e=>()=>e),a=Sf(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.host},e=>()=>e),s=Sf(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.locale},e=>()=>e),d=Sf(e=>e.meta&&e.meta.variantIdentificationToken,e=>()=>e),c=Sf(e=>e.errors.loadError,e=>()=>e),l=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((u=iv,h)=>({getConfig:e(u),getFlashMessages:t(u),getStoreConfig:n(u,{formState:h}),getStoreConfigOrThrow:i(u,{formState:h}),getContextConfig:r(u),getExternalSource:o(u),getHost:a(u),getLocale:s(u),getVariantIdentificationToken:d(u),getLoadError:c(u),isLoading:l(u)}))}(),o=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.errors.loadError,e=>()=>e),n=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=jv)=>({getCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),a=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.errors.removeCouponError,e=>()=>e),n=Sf(e=>e.errors.applyCouponError,e=>()=>e),i=Sf(e=>!!e.statuses.isApplyingCoupon,e=>()=>e),r=Sf(e=>!!e.statuses.isRemovingCoupon,e=>()=>e);return Oe((o=dv)=>({getCoupons:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),s=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingCustomer))),n=Sf(e=>e.errors.createError,e=>()=>e),i=Sf(e=>!!e.statuses.isCreating,e=>()=>e),r=Sf(e=>e.errors.createAddressError,e=>()=>e),o=Sf(e=>!!e.statuses.isCreatingAddress,e=>()=>e);return Oe((a=vv)=>({getCustomer:e(a),getCustomerOrThrow:t(a),getCreateAccountError:n(a),isCreatingCustomerAccount:i(a),getCreateAddressError:r(a),isCreatingCustomerAddress:o(a)}))}(),d=function(){const e=Sf(e=>e.errors.signInMethodId,e=>e.errors.signInError,(e,t)=>n=>{if(!n||e===n)return t}),t=Sf(e=>e.errors.signOutMethodId,e=>e.errors.signOutError,(e,t)=>n=>{if(!n||e===n)return t}),n=Sf(e=>e.errors.executePaymentMethodCheckoutMethodId,e=>e.errors.executePaymentMethodCheckoutError,(e,t)=>n=>{if(!n||e===n)return t}),i=Sf(e=>e.errors.initializeMethodId,e=>e.errors.initializeErrors,(e,t)=>n=>{if(e&&t)return n?t[n]:t[e]}),r=Sf(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),o=Sf(e=>e.statuses.signInMethodId,e=>e.statuses.isSigningIn,(e,t)=>n=>!(n&&e!==n||!t)),a=Sf(e=>e.statuses.signOutMethodId,e=>e.statuses.isSigningOut,(e,t)=>n=>!(n&&e!==n||!t)),s=Sf(e=>e.statuses.executePaymentMethodCheckoutMethodId,e=>e.statuses.isExecutingPaymentMethodCheckout,(e,t)=>n=>!(n&&e!==n||!t)),d=Sf(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),c=Sf(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),l=Sf(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((u=Cv)=>({getSignInError:e(u),getSignOutError:t(u),getExecutePaymentMethodCheckoutError:n(u),getInitializeError:i(u),getWidgetInteractionError:r(u),isSigningIn:o(u),isSigningOut:a(u),isExecutingPaymentMethodCheckout:s(u),isInitializing:d(u),isInitialized:c(u),isWidgetInteracting:l(u)}))}(),c=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.errors.removeGiftCertificateError,e=>()=>e),n=Sf(e=>e.errors.applyGiftCertificateError,e=>()=>e),i=Sf(e=>!!e.statuses.isApplyingGiftCertificate,e=>()=>e),r=Sf(e=>!!e.statuses.isRemovingGiftCertificate,e=>()=>e);return Oe((o=pv)=>({getGiftCertificates:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),l=function(){const e=Sf(e=>e.data,e=>t=>{if(!e)return;const n=t.gateway?`${t.gateway}.${t.id}`:t.id,i=hS[n];return i?L(e,i):[]}),t=Sf(e=>e.data,(e=[])=>t=>{const n=Ce(hS);return e.find(e=>e.bigpayToken===t&&"card"===e.type&&n.some(t=>K(e,t)))}),n=Sf(t,e=>t=>lS(e(t),()=>new ot(tt.MissingPaymentInstrument))),i=Sf(e=>e.data,e=>()=>{if(e)return U(hS,t=>L(e,e=>K(e,t)))}),r=Sf(e=>e.meta,e=>()=>e),o=Sf(e=>e.errors.loadError,e=>()=>e),a=Sf(e=>e.errors.failedInstrument,e=>e.errors.deleteError,(e,t)=>n=>{if(!n||e===n)return t}),s=Sf(e=>e.statuses.isLoading,e=>()=>!!e),d=Sf(e=>e.statuses.deletingInstrument,e=>e.statuses.isDeleting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=y_)=>({getCardInstrument:t(c),getCardInstrumentOrThrow:n(c),getInstruments:i(c),getInstrumentsByPaymentMethod:e(c),getInstrumentsMeta:r(c),getLoadError:o(c),getDeleteError:a(c),isLoading:s(c),isDeleting:d(c)}))}(),u=function(){const e=Sf(e=>e.data,e=>(t=[],n)=>{const i=j(t,{code:n});return(e?e.shippingAddress:[]).map(e=>a(e,t,i))}),t=Sf(e=>e.data,e=>(t=[],n)=>{const i=j(t,{code:n});return(e?e.billingAddress:[]).map(e=>a(e,t,i))}),n=Sf(e=>e.data,e=>()=>e?e.customerAccount:[]),i=Sf(e=>e.extraFields,e=>()=>e&&e.address.length?e.address.map(Ye):[]),r=Sf(e=>e.errors.loadError,e=>()=>e),o=Sf(e=>!!e.statuses.isLoading,e=>()=>e);function a(e,t,n){return"countryCode"===e.name?function(e,t=[],n){if(!t.length)return e;const{code:i=""}=n||{},r=t.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{options:{items:r},default:i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,t,n):"stateOrProvince"===e.name?function(e,t){const{subdivisions:n=[],requiresState:i}=t||{};if(!n.length)return Object.assign(Object.assign({},e),{required:null!=i&&i});const r=n.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{name:"stateOrProvinceCode",options:{items:r},required:null==i||i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,n):"postalCode"===e.name?function(e,t){const{hasPostalCodes:n=[]}=t||{};return void 0===n?e:Object.assign(Object.assign({},e),{required:Boolean(n)})}(e,n):e}return Oe((a=zv)=>({getShippingAddressFields:e(a),getBillingAddressFields:t(a),getCustomerAccountFields:n(a),getAddressExtraFields:i(a),getLoadError:r(a),isLoading:o(a)}))}(),h=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.meta,e=>()=>e),n=Sf(e=>e.data,e=>(t,n)=>j(e,n?{id:t,gateway:n}:{id:t})),i=Sf(n,e=>(t,n)=>lS(e(t,n),()=>new ot(tt.MissingPaymentMethod))),r=Sf(e=>e.errors.loadError,e=>()=>e),o=Sf(e=>e.errors.loadMethodId,e=>e.errors.loadMethodError,(e,t)=>n=>{if(!n||e===n)return t}),a=Sf(e=>e.statuses.isLoading,e=>()=>!!e),s=Sf(e=>e.statuses.loadMethodId,e=>e.statuses.isLoadingMethod,(e,t)=>n=>!(n&&e!==n||!t));return Oe((d=t_)=>({getPaymentMethods:e(d),getPaymentMethodsMeta:t(d),getPaymentMethod:n(d),getPaymentMethodOrThrow:i(d),getLoadError:r(d),getLoadMethodError:o(d),isLoading:a(d),isLoadingMethod:s(d)}))}(),p=function(){const e=Sf(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),t=Sf(e=>e.errors.executeMethodId,e=>e.errors.executeError,(e,t)=>n=>{if(!n||e===n)return t}),n=Sf(e=>e.errors.finalizeMethodId,e=>e.errors.finalizeError,(e,t)=>n=>{if(!n||e===n)return t}),i=Sf(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=Sf(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),o=Sf(e=>e.data,e=>t=>{const n=t.gatewayId?`${t.methodId}.${t.gatewayId}`:t.methodId;return!(!e[n]||!e[n].isInitialized)}),a=Sf(e=>e.statuses.executeMethodId,e=>e.statuses.isExecuting,(e,t)=>n=>!(n&&e!==n||!t)),s=Sf(e=>e.statuses.finalizeMethodId,e=>e.statuses.isFinalizing,(e,t)=>n=>!(n&&e!==n||!t)),d=Sf(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=s_)=>({getInitializeError:e(c),getExecuteError:t(c),getFinalizeError:n(c),getWidgetInteractingError:i(c),isInitializing:r(c),isInitialized:o(c),isExecuting:a(c),isFinalizing:s(c),isWidgetInteracting:d(c)}))}(),m=function(){const e=Sf(e=>e.data,e=>(t,n)=>{if(!e)return;const i=k_(T_({consignmentId:t,searchArea:n})),r=btoa(`${JSON.stringify(i)}`);return e[r]}),t=Sf(e=>e.errors.loadError,e=>()=>e),n=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=D_)=>({getPickupOptions:e(i),getLoadError:t(i),isLoading:n(i)}))}(),y=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingPaymentProviderCustomer)));return Oe((n=h_)=>({getPaymentProviderCustomer:e(n),getPaymentProviderCustomerOrThrow:t(n)}))}(),g=function(){const e=Sf(e=>e.data,e=>t=>e[t]);return Oe((t=I_)=>({getCheckout:e(t)}))}(),f=function(){const e=Sf(e=>e.data,e=>()=>{const t=null==e?void 0:e.find(e=>!e.selectedPickupOption);return null==t?void 0:t.shippingAddress}),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingShippingAddress))),n=Sf(e=>e.data,e=>()=>{const t=null==e?void 0:e.filter(e=>!e.selectedPickupOption);return t?t.map(e=>e.shippingAddress):[]}),i=Sf(n,e=>()=>lS(e(),()=>new ot(tt.MissingShippingAddress)));return Oe((r=b_)=>({getShippingAddress:e(r),getShippingAddressOrThrow:t(r),getShippingAddresses:n(r),getShippingAddressesOrThrow:i(r)}))}(),v=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.errors.loadError,e=>()=>e),n=Sf(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((i=R_)=>({getShippingCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),_=function(){const e=Sf(e=>e.errors.updateAddressMethodId,e=>e.errors.updateAddressError,(e,t)=>n=>{if(!n||e===n)return t}),t=Sf(e=>e.errors.selectOptionMethodId,e=>e.errors.selectOptionError,(e,t)=>n=>{if(!n||e===n)return t}),n=Sf(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),i=Sf(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=Sf(e=>e.statuses.updateAddressMethodId,e=>e.statuses.isUpdatingAddress,(e,t)=>n=>!(n&&e!==n||!t)),o=Sf(e=>e.statuses.selectOptionMethodId,e=>e.statuses.isSelectingOption,(e,t)=>n=>!(n&&e!==n||!t)),a=Sf(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),s=Sf(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),d=Sf(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=U_)=>({getUpdateAddressError:e(c),getSelectOptionError:t(c),getInitializeError:n(c),getWidgetInteractionError:i(c),isUpdatingAddress:r(c),isSelectingOption:o(c),isInitializing:a(c),isInitialized:s(c),isWidgetInteracting:d(c)}))}(),S=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingConsignments))),n=Sf(e=>e.data,e=>t=>{if(e&&e.length)return j(e,{id:t})}),i=Sf(e=>e.data,e=>t=>{if(e&&e.length)return j(e,e=>{return n=e.shippingAddress,i=t,Y(pS(n),pS(i));var n,i})}),r=Sf(e=>e.data,e=>()=>{if(e&&e.length)return e[0].selectedShippingOption}),o=Sf(e=>e.errors.loadError,e=>()=>e),a=Sf(e=>e.errors.createError,e=>()=>e),s=Sf(e=>e.errors.loadShippingOptionsError,e=>()=>e),d=Sf(e,(e,{cart:t})=>t.getCart,(e,t)=>()=>{const n=t();if(!n)return[];const i=(e()||[]).reduce((e,t)=>e.concat(t.lineItemIds),[]);return(n.lineItems.physicalItems||[]).filter(e=>i.indexOf(e.id)<0)}),c=Sf(e=>e.errors.updateError,e=>t=>t?e[t]:j(e)),l=Sf(e=>e.errors.deleteError,e=>t=>t?e[t]:j(e)),u=Sf(i,c,a,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),h=Sf(e=>e.errors.updateShippingOptionError,e=>t=>t?e[t]:j(e)),p=Sf(e=>e.statuses.isLoading,e=>()=>!0===e),m=Sf(e=>e.statuses.isLoadingShippingOptions,e=>()=>!0===e),y=Sf(e=>e.statuses.isCreating,e=>()=>!0===e),g=Sf(e=>e.statuses.isUpdating,e=>t=>t?!0===e[t]:!0===j(e)),f=Sf(e=>e.statuses.isDeleting,e=>t=>t?!0===e[t]:!0===j(e)),v=Sf(i,g,y,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),_=Sf(e=>e.statuses.isUpdatingShippingOption,e=>t=>t?!0===e[t]:!0===j(e));return Oe((S=b_,I)=>({getConsignments:e(S),getConsignmentsOrThrow:t(S),getConsignmentById:n(S),getConsignmentByAddress:i(S),getShippingOption:r(S),getLoadError:o(S),getCreateError:a(S),getLoadShippingOptionsError:s(S),getUnassignedItems:d(S,{cart:I}),getUpdateError:c(S),getDeleteError:l(S),getItemAssignmentError:u(S),getUpdateShippingOptionError:h(S),isLoading:p(S),isLoadingShippingOptions:m(S),isCreating:y(S),isUpdating:g(S),isDeleting:f(S),isAssigningItems:v(S),isUpdatingShippingOption:_(S)}))}(),I=function(){const e=Sf(e=>e.data,(e,{billingAddress:t})=>t.getBillingAddress,(e,{cart:t})=>t.getCart,(e,{customer:t})=>t.getCustomer,(e,{consignments:t})=>t.getConsignments,(e,{coupons:t})=>t.getCoupons,(e,{giftCertificates:t})=>t.getGiftCertificates,(e,t,n,i,r,o,a)=>()=>{const s=t(),d=n(),c=i(),l=r()||[],u=o()||[],h=a()||[];if(e&&d&&c)return Object.assign(Object.assign({},e),{billingAddress:s,cart:d,customer:c,consignments:l,coupons:u,giftCertificates:h})}),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingCheckout))),n=Sf(e,e=>t=>{const n=e();if(!n)return;const i=n.grandTotal||0,r=n.customer.storeCredit||0;return t?Math.max(i-r,0):n.outstandingBalance}),i=Sf(e=>e.errors.loadError,e=>()=>e),r=Sf(e=>e.errors.updateError,e=>()=>e),o=Sf(e=>e.statuses.isExecutingSpamCheck,e=>()=>!0===e),a=Sf(e=>e.statuses.isLoading,e=>()=>!0===e),s=Sf(e=>e.statuses.isUpdating,e=>()=>!0===e);return Oe((d=oS,c,l,u,h,p,m)=>({getCheckout:e(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getCheckoutOrThrow:t(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getOutstandingBalance:n(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getLoadError:i(d),getUpdateError:r(d),isExecutingSpamCheck:o(d),isLoading:a(d),isUpdating:s(d)}))}(),w=function(){const e=Sf(e=>e.data,(e,{billingAddress:t})=>t.getOrderBillingAddress(),(e,{coupons:t})=>t.getCoupons(),(e,t,n=[])=>()=>{if(e&&t)return Object.assign(Object.assign({},e),{billingAddress:t,coupons:n})}),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingOrder))),n=Sf(e=>e.meta,e=>()=>e),i=Sf(e=>e.errors.loadError,e=>()=>e),r=Sf(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.payments},(e=[])=>t=>{const n=e.find(({providerId:e})=>e===t);return null==n?void 0:n.paymentId}),o=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((a=Gv,s,d)=>({getOrder:e(a,{billingAddress:s,coupons:d}),getOrderOrThrow:t(a,{billingAddress:s,coupons:d}),getOrderMeta:n(a),getLoadError:i(a),getPaymentId:r(a),isLoading:o(a)}))}(),C=function(){const e=Sf(e=>e.data,e=>()=>e);return Oe((t=Jv)=>({getOrderBillingAddress:e(t)}))}(),b=function(){const e=Sf(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.payment}),t=Sf(({order:e})=>e.getOrder,e=>()=>{const t=e();return j(t&&t.payments,({providerId:e})=>"giftcertificate"!==e&&"storecredit"!==e)}),n=Sf(({checkout:e})=>e.getCheckout,e=>()=>{const t=e();return j(t&&t.payments,({providerType:e})=>"PAYMENT_TYPE_HOSTED"===e)}),i=Sf(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.id)return{providerId:i.id,gatewayId:i.gateway};const r=t()||n();return r&&r.providerId?{providerId:r.providerId,gatewayId:r.gatewayId}:void 0}),r=Sf(i,e=>()=>lS(e(),()=>new ot(tt.MissingPaymentId))),o=Sf(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.status)return i.status.replace("PAYMENT_STATUS_","");const r=t()||n();return r?r.detail.step:void 0}),a=Sf(o,e=>()=>lS(e(),()=>new ot(tt.MissingPaymentStatus))),s=Sf(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.token}),d=Sf(s,e=>()=>lS(e(),()=>new ot(tt.MissingPaymentToken))),c=Sf(e,e=>()=>{const t=e();return t&&t.redirectUrl}),l=Sf(c,e=>()=>lS(e(),()=>new ot(tt.MissingPaymentRedirectUrl))),u=Sf(({checkout:e})=>e.getOutstandingBalance,e=>(t=!1)=>{const n=e(t);return!!n&&n>0}),h=Sf(o,e=>t=>!(!t||!t.nonce)||"ACKNOWLEDGE"===e()||e()===$y);return Oe((e,t)=>({getPaymentId:i({checkout:e,order:t}),getPaymentIdOrThrow:r({checkout:e,order:t}),getPaymentStatus:o({checkout:e,order:t}),getPaymentStatusOrThrow:a({checkout:e,order:t}),getPaymentToken:s({checkout:e,order:t}),getPaymentTokenOrThrow:d({checkout:e,order:t}),getPaymentRedirectUrl:c({checkout:e,order:t}),getPaymentRedirectUrlOrThrow:l({checkout:e,order:t}),isPaymentDataRequired:u({checkout:e,order:t}),isPaymentDataSubmitted:h({checkout:e,order:t})}))}(),P=function(){const e=Sf(e=>e.errors.applyError,e=>()=>e),t=Sf(e=>!!e.statuses.isApplying,e=>()=>e);return Oe((n=mS)=>({getApplyError:e(n),isApplying:t(n)}))}(),O=function(){const e=Sf(e=>e.errors.updateError,e=>()=>e),t=Sf(e=>!!e.statuses.isUpdating,e=>()=>e);return Oe((n=tS)=>({getUpdateError:e(n),isUpdating:t(n)}))}(),E=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.errors.sendError,e=>()=>e),n=Sf(e=>!!e.statuses.isSending,e=>()=>e);return Oe((i=W_)=>({getEmail:e(i),getSendError:t(i),isSending:n(i)}))}(),A=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.data,e=>t=>null==e?void 0:e.find(e=>e.region===t)),n=Sf(e=>e.errors.loadError,e=>()=>e),i=Sf(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((r=Av)=>({getExtensions:e(r),getExtensionByRegion:t(r),getLoadError:n(r),isLoading:i(r)}))}();return(T,k={})=>{const D=e(T.b2bToken),M=t(T.billingAddress),z=n(T.cart),x=i(T.checkoutButton),N=o(T.countries),R=a(T.coupons),F=s(T.customer),L=d(T.customerStrategies),j=A(T.extensions),B=u(T.formFields),U=c(T.giftCertificates),q=l(T.instruments),V=C(T.orderBillingAddress),G=h(T.paymentMethods),H=y(T.paymentProviderCustomer),W=p(T.paymentStrategies),$=m(T.pickupOptions),Y=g(T.remoteCheckout),K=f(T.consignments),J=v(T.shippingCountries),Z=_(T.shippingStrategies),Q=O(T.subscriptions),X=P(T.storeCredit),ee=E(T.signInEmail),te=S(T.consignments,z),ne=I(T.checkout,M,z,te,R,F,U),ie=w(T.order,V,R),re=b(ne,ie),oe={b2bToken:D,billingAddress:M,cart:z,checkout:ne,checkoutButton:x,config:r(T.config,T.formFields),consignments:te,countries:N,coupons:R,customer:F,customerStrategies:L,extensions:j,form:B,giftCertificates:U,instruments:q,order:ie,orderBillingAddress:V,payment:re,paymentMethods:G,paymentProviderCustomer:H,paymentStrategies:W,pickupOptions:$,remoteCheckout:Y,shippingAddress:K,shippingCountries:J,shippingStrategies:Z,signInEmail:ee,subscriptions:Q,storeCredit:X};return k.shouldWarnMutation?function(e){return Object.keys(e).reduce((t,n)=>(t[n]=uS(e[n]),t),{})}(oe):oe}}function gS(e={},t){const n=(o=function(){const e=new Pf;return["catalog_only","empty_cart","invalid_order_id","invalid_order_token","missing_order_token","missing_provider_token","missing_shipping_method","order_completion_error","order_could_not_be_finalized_error","order_create_failed","provider_fatal_error","provider_setup_error","stock_too_low"].forEach(t=>{e.register(t,(e,t)=>new wf(e,t))}),e.register("invalid_payment_provider",e=>new Xr(e)),e.register("payment_config_not_found",e=>new Xr(e)),e}(),e=>_(e).pipe(P(e=>{if(e instanceof Error||e.payload instanceof Error)throw e;if((t=e.payload)&&"object"==typeof t&&["body","headers","status","statusText"].every(e=>Object.prototype.hasOwnProperty.call(t,e))){const t=e.payload.body&&e.payload.body.detail;throw Object.assign(Object.assign({},e),{payload:o.createError(e.payload,t)})}var t;throw e}))),i=yS(),r=d({b2bToken:Df,billingAddress:Ff,cart:Gf,checkout:aS,checkoutButton:Xf,config:rv,consignments:P_,countries:Bv,coupons:cv,customer:_v,customerStrategies:bv,extensions:Tv,formFields:xv,giftCertificates:mv,instruments:g_,orderBillingAddress:Zv,order:Hv,payment:Xv,paymentMethods:n_,paymentStrategies:d_,pickupOptions:M_,paymentProviderCustomer:p_,remoteCheckout:w_,shippingCountries:F_,shippingStrategies:q_,signInEmail:$_,subscriptions:nS,storeCredit:Q_});var o;return u(r,e,Object.assign({actionTransformer:n,stateTransformer:e=>i(e)},t))}function fS(e){var t;"https:"!==document.location.protocol&&wt().warn("The BigCommerce Checkout SDK should not be used on a non-HTTPS page");const i=null!==(t=null==e?void 0:e.rollOutLazyPaymentStrategies)&&void 0!==t&&t;"production"!==vt()&&wt().warn("Note that the development build is not optimized. To create a production build, set process.env.NODE_ENV to `production`.");const r={meta:{externalSource:e&&e.externalSource,host:null==e?void 0:e.host,locale:null==e?void 0:e.locale,variantIdentificationToken:window.checkoutVariantIdentificationToken},errors:{},statuses:{}},{locale:s="",shouldWarnMutation:d=!0}=e||{},c=n({host:e&&e.host}),l=gS({config:r},{shouldWarnMutation:d}),u=new ft(c,{getBasePath:()=>{var e,t;return null!==(t=null===(e=l.getState().config.getStoreConfig())||void 0===e?void 0:e.links.baseUrl)&&void 0!==t?t:void 0},getFeatures:()=>{var e,t,n;return null!==(n=null===(t=null===(e=l.getState().config.getStoreConfig())||void 0===e?void 0:e.checkoutSettings)||void 0===t?void 0:t.features)&&void 0!==n?n:{}}}),h=Gm(l),p=new Bm(u),m=new tn(u),y=new Pt(new kt(c)),g=Sn(o()),f=new In(u),v=new mn(g,f),_=new Vm(p,new ny(m)),S=new Rg(new Fg(u)),I=new an(new sn(u)),w=new rn(m,y,I),C=$g(l,u),b=function(e,t,n={useFallback:!1}){const{useFallback:i}=n,r=new Ht(i);for(const[,n]of Object.entries(t))if(qt(n))for(const t of n.resolveIds)r.register(t,()=>n(e));return r}(C,i?{createNoPaymentStrategy:Pd}:He,{useFallback:!0}),P=function(e,t){const n=new Ht;for(const[,i]of Object.entries(t))if(qt(i))for(const t of i.resolveIds)n.register(t,()=>i(e));return n}(C,i?{}:Ge),O=new Rn(new Fn(u)),E=new Wn,A=new Jn(l,E),T=yt(l,function(){const e=function(){const e=Sf(({checkout:e})=>e.getCheckout,e=>Ug(e)),t=Sf(({order:e})=>e.getOrder,e=>Ug(e)),n=Sf(({config:e})=>e.getStoreConfig,e=>Ug(e)),i=Sf(({shippingAddress:e})=>e.getShippingAddress,({config:e})=>e.getContextConfig,(e,t)=>Ug(()=>{const n=e(),i=t();if(!n){if(!i||!i.geoCountryCode)return;return{firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}}return n})),r=Sf(({consignments:e})=>e.getConsignments,e=>Ug(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.availableShippingOptions})),o=Sf(({consignments:e})=>e.getConsignments,e=>Ug(e)),a=Sf(({consignments:e})=>e.getConsignments,e=>Ug(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.selectedShippingOption})),s=Sf(({shippingCountries:e})=>e.getShippingCountries,e=>Ug(e)),d=Sf(({billingAddress:e})=>e.getBillingAddress,({config:e})=>e.getContextConfig,(e,t)=>Ug(()=>{const n=e(),i=t();return(!n||Ce(le(n,"shouldSaveAddress","email","id")).every(e=>!e||!e.length))&&i&&i.geoCountryCode?{id:n?n.id:"",firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",email:n?n.email:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}:n})),c=Sf(({countries:e})=>e.getCountries,e=>Ug(e)),l=Sf(({paymentMethods:e})=>e.getPaymentMethods,e=>Ug(e)),u=Sf(({paymentMethods:e})=>e.getPaymentMethod,e=>Ug(e)),h=Sf(({payment:e})=>e.getPaymentId,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Ug(()=>{const n=e();return n&&t(n.providerId,n.gatewayId)})),p=Sf(({cart:e})=>e.getCart,e=>Ug(e)),m=Sf(({coupons:e})=>e.getCoupons,e=>Ug(e)),y=Sf(({giftCertificates:e})=>e.getGiftCertificates,e=>Ug(e)),g=Sf(({customer:e})=>e.getCustomer,e=>Ug(e)),f=Sf(({signInEmail:e})=>e.getEmail,e=>Ug(e)),v=Sf(({b2bToken:e})=>e.getToken,e=>Ug(e)),_=Sf(({payment:e})=>e.isPaymentDataRequired,e=>Ug(e)),S=Sf(({payment:e})=>e.isPaymentDataSubmitted,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Ug((n,i)=>e(t(n,i)))),I=Sf(({instruments:e})=>e.getInstruments,({instruments:e})=>e.getInstrumentsByPaymentMethod,(e,t)=>Ug(function(n){return n?t(n):e()})),w=Sf(({form:e})=>e.getCustomerAccountFields,e=>Ug(e)),C=Sf(({form:e})=>e.getBillingAddressFields,({countries:e})=>e.getCountries,(e,t)=>Ug(n=>e(t(),n))),b=Sf(({form:e})=>e.getShippingAddressFields,({shippingCountries:e})=>e.getShippingCountries,(e,t)=>Ug(n=>e(t(),n))),P=Sf(({form:e})=>e.getAddressExtraFields,e=>Ug(e)),O=Sf(({config:e})=>e.getFlashMessages,e=>Ug(e)),E=Sf(({pickupOptions:e})=>e.getPickupOptions,e=>Ug(e)),A=Sf(({config:e})=>e.getStoreConfig,e=>Ug(()=>{const t=e();if(t)return t.checkoutSettings.checkoutUserExperienceSettings})),T=Sf(({extensions:e})=>e.getExtensions,e=>Ug(e)),k=Sf(({paymentProviderCustomer:e})=>e.getPaymentProviderCustomer,e=>Ug(e)),D=Sf(({extensions:e})=>e.getExtensionByRegion,e=>Ug(e));return Oe(M=>({getCheckout:e(M),getOrder:t(M),getConfig:n(M),getExtensions:T(M),getExtensionByRegion:D(M),getFlashMessages:O(M),getShippingAddress:i(M),getShippingOptions:r(M),getConsignments:o(M),getSelectedShippingOption:a(M),getShippingCountries:s(M),getBillingAddress:d(M),getBillingCountries:c(M),getPaymentMethods:l(M),getPaymentMethod:u(M),getSelectedPaymentMethod:h(M),getCart:p(M),getCoupons:m(M),getGiftCertificates:y(M),getCustomer:g(M),isPaymentDataRequired:_(M),isPaymentDataSubmitted:S(M),getSignInEmail:f(M),getB2BToken:v(M),getInstruments:I(M),getCustomerAccountFields:w(M),getBillingAddressFields:C(M),getShippingAddressFields:b(M),getAddressExtraFields:P(M),getPickupOptions:E(M),getUserExperienceSettings:A(M),getPaymentProviderCustomer:k(M)}))}(),t=function(){const e=If(e=>e,e=>()=>{for(const t of Object.keys(e)){const n=e[t]();if(n)return n}}),t=Sf(({shippingStrategies:e})=>e.getSelectOptionError,({consignments:e})=>e.getUpdateShippingOptionError,(e,t)=>n=>e()||t(n));return Oe(n=>{const i={getLoadCheckoutError:n.checkout.getLoadError,getUpdateCheckoutError:n.checkout.getUpdateError,getSubmitOrderError:n.paymentStrategies.getExecuteError,getFinalizeOrderError:n.paymentStrategies.getFinalizeError,getLoadOrderError:n.order.getLoadError,getLoadCartError:n.cart.getLoadError,getLoadBillingCountriesError:n.countries.getLoadError,getLoadShippingCountriesError:n.shippingCountries.getLoadError,getLoadPaymentMethodsError:n.paymentMethods.getLoadError,getLoadPaymentMethodError:n.paymentMethods.getLoadMethodError,getInitializePaymentError:n.paymentStrategies.getInitializeError,getSignInError:n.customerStrategies.getSignInError,getSignOutError:n.customerStrategies.getSignOutError,getInitializeCustomerError:n.customerStrategies.getInitializeError,getLoadShippingOptionsError:n.consignments.getLoadShippingOptionsError,getSelectShippingOptionError:t(n),getContinueAsGuestError:n.billingAddress.getContinueAsGuestError,getUpdateBillingAddressError:n.billingAddress.getUpdateError,getUpdateSubscriptionsError:n.subscriptions.getUpdateError,getUpdateShippingAddressError:n.shippingStrategies.getUpdateAddressError,getDeleteConsignmentError:n.consignments.getDeleteError,getUpdateConsignmentError:n.consignments.getUpdateError,getCreateConsignmentsError:n.consignments.getCreateError,getInitializeShippingError:n.shippingStrategies.getInitializeError,getApplyStoreCreditError:n.storeCredit.getApplyError,getApplyCouponError:n.coupons.getApplyError,getRemoveCouponError:n.coupons.getRemoveError,getApplyGiftCertificateError:n.giftCertificates.getApplyError,getRemoveGiftCertificateError:n.giftCertificates.getRemoveError,getLoadInstrumentsError:n.instruments.getLoadError,getDeleteInstrumentError:n.instruments.getDeleteError,getLoadConfigError:n.config.getLoadError,getSignInEmailError:n.signInEmail.getSendError,getLoadB2BTokenError:n.b2bToken.getLoadError,getCreateCustomerAccountError:n.customer.getCreateAccountError,getCreateCustomerAddressError:n.customer.getCreateAddressError,getPickupOptionsError:n.pickupOptions.getLoadError,getLoadExtensionsError:n.extensions.getLoadError};return Object.assign({getError:e(i)},i)})}(),n=function(){const e=If(e=>e,e=>()=>Object.keys(e).some(t=>e[t]())),t=Sf(({shippingStrategies:e})=>e.isSelectingOption,({consignments:e})=>e.isUpdatingShippingOption,(e,t)=>n=>e()||t(n)),n=Sf(({customerStrategies:e})=>e.isInitializing,({customerStrategies:e})=>e.isSigningIn,({customerStrategies:e})=>e.isSigningOut,({customerStrategies:e})=>e.isExecutingPaymentMethodCheckout,({customerStrategies:e})=>e.isWidgetInteracting,(e,t,n,i,r)=>o=>e(o)||t(o)||n(o)||i(o)||r(o)),i=Sf(({shippingStrategies:e})=>e.isInitializing,({shippingStrategies:e})=>e.isUpdatingAddress,({shippingStrategies:e})=>e.isSelectingOption,({shippingStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),r=Sf(({paymentStrategies:e})=>e.isInitializing,({paymentStrategies:e})=>e.isExecuting,({paymentStrategies:e})=>e.isFinalizing,({paymentStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),o=Sf(({paymentStrategies:e})=>e.isExecuting,({checkout:e})=>e.isExecutingSpamCheck,(e,t)=>n=>e(n)||t());return Oe(a=>{const s={isLoadingCheckout:a.checkout.isLoading,isUpdatingCheckout:a.checkout.isUpdating,isExecutingSpamCheck:a.checkout.isExecutingSpamCheck,isSubmittingOrder:o(a),isFinalizingOrder:a.paymentStrategies.isFinalizing,isLoadingOrder:a.order.isLoading,isLoadingCart:a.cart.isLoading,isLoadingBillingCountries:a.countries.isLoading,isLoadingShippingCountries:a.shippingCountries.isLoading,isLoadingPaymentMethods:a.paymentMethods.isLoading,isLoadingPaymentMethod:a.paymentMethods.isLoadingMethod,isInitializingPayment:a.paymentStrategies.isInitializing,isSigningIn:a.customerStrategies.isSigningIn,isSigningOut:a.customerStrategies.isSigningOut,isExecutingPaymentMethodCheckout:a.customerStrategies.isExecutingPaymentMethodCheckout,isInitializingCustomer:a.customerStrategies.isInitializing,isInitializedCustomer:a.customerStrategies.isInitialized,isLoadingShippingOptions:a.consignments.isLoadingShippingOptions,isSelectingShippingOption:t(a),isUpdatingBillingAddress:a.billingAddress.isUpdating,isUpdatingSubscriptions:a.subscriptions.isUpdating,isCreatingCustomerAccount:a.customer.isCreatingCustomerAccount,isCreatingCustomerAddress:a.customer.isCreatingCustomerAddress,isContinuingAsGuest:a.billingAddress.isContinuingAsGuest,isUpdatingShippingAddress:a.shippingStrategies.isUpdatingAddress,isUpdatingConsignment:a.consignments.isUpdating,isDeletingConsignment:a.consignments.isDeleting,isCreatingConsignments:a.consignments.isCreating,isInitializingShipping:a.shippingStrategies.isInitializing,isApplyingStoreCredit:a.storeCredit.isApplying,isApplyingCoupon:a.coupons.isApplying,isRemovingCoupon:a.coupons.isRemoving,isApplyingGiftCertificate:a.giftCertificates.isApplying,isRemovingGiftCertificate:a.giftCertificates.isRemoving,isLoadingInstruments:a.instruments.isLoading,isDeletingInstrument:a.instruments.isDeleting,isLoadingConfig:a.config.isLoading,isSendingSignInEmail:a.signInEmail.isSending,isLoadingB2BToken:a.b2bToken.isLoading,isCustomerStepPending:n(a),isShippingStepPending:i(a),isPaymentStepPending:r(a),isLoadingPickupOptions:a.pickupOptions.isLoading};return Object.assign({isPending:e(s)},s)})}();return i=>({data:e(i),errors:t(i),statuses:n(i)})}());return new vf(l,T,A,function(e,t){const n={[Yn.ConsignmentsChanged]:Qn};return new Zn(e,t,n)}(T,A),new Xe(new it(c)),new dt(new ht(u),S),w,y,new Jt(new Zt(u),w,v),new Pg(new Eg(u),m),new zm(new xm(u,{locale:s})),new Mt(new jt(u)),new Xt(function(e,t){const n=new Gt,i=a(),r=new tn(t),o=new rn(r,new Pt(new kt(t)),new an(new sn(t))),s=new mn(Sn(i),new In(t)),d=new Jt(new Zt(t),o,s);return n.register("default",()=>new wn(e,d)),n}(l,u),P,C),new gt,new Bt(new Ut(u)),new Yg(new Xg(h,u)),_,new Wm(new $m(u)),new Xm(function(e,t,n){const i=new Wy({defaultToken:Zm.CREDIT_CARD}),r=a(),s=new Gy,d=new by(t),c=new tn(n),l=new ny(c),u=new Vm(new Bm(n),l),h=new cy(Sn(o())),p=new Cy(d,u,s,h),m=Ee(),y=((e,t)=>new ig(new ng(e,t)))(m,h),g=new wy(e);return i.register(Zm.CONVERGE,()=>new Zy(e,u,p,g,m)),i.register(Zm.PPSDK,()=>new dg(e,u,((e,t,n,i,r)=>{const o=new lg;return o.register(ag.CARD,()=>new hg(e,t,r,i)),o.register(ag.NONE,()=>new pg(n,i)),o.register(ag.UNSUPPORTED,()=>{}),o})(e,u,n,y,g),new fg(n,y),new iy("PPSDK"))),i.register(Zm.WE_PAY,()=>new vg(e,u,p,g,new _g(r))),i}(l,h,u),b,_,v,C),new ef(new tf(u)),new kg(new Dg(u,{locale:s}),l),new nf(function(e,t){const n=new Gt,i=$g(e),r=new tn(t),o=new Eg(t),s=new Pg(o,r),d=new Wm(new $m(t)),c=a(),l=new Rg(new Fg(t)),u=new dt(new ht(t),l),h=window,p=new Ei(i);return n.register("amazonpay",()=>new af(e,s,new Wm(new $m(t)),gi(),new nf(n))),n.register("stripeupe",()=>new pf(e,new Ra(c),s,d)),n.register("braintreeacceleratedcheckout",()=>new df(e,u,s,d,new Ig,new So(new Hi(a(),h,p),h))),n.register("paypalcommerceacceleratedcheckout",()=>new uf(e,u,s,d,new Ig,Cs(),nd())),n.register("default",()=>new cf(e,s)),n}(l,u)),new mf(new yf(u)),v,new zg(new xg(u)),S,I,O,E)}const vS=e=>{const t=we(e);return document.getElementById(t)?vS(e):t};function _S(e){return Object.prototype.hasOwnProperty.call(e,"cacheKey")}class SS{constructor(e){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=Object.assign({maxSize:0,isEqual:je,onExpire:ce},e)}getKey(...e){const t=this._resolveMap(...e),{index:n,parentMap:i}=t;let{map:r}=t;return r&&r.cacheKey?r.usedCount++:r=this._generateMap(i,e.slice(n)),this._removeLeastUsedMap(r),r.cacheKey}getUsedCount(...e){const{map:t}=this._resolveMap(...e);return t?t.usedCount:0}_resolveMap(...e){let t=0,n=this._map;for(;n.maps.length;){let i=!1;for(let r=0;r<n.maps.length;r++){const o=n.maps[r];if(this._options.isEqual(o.value,e[t])){if(n.maps.unshift(...n.maps.splice(r,1)),(0===e.length||t===e.length-1)&&_S(o))return{index:t,map:o,parentMap:n};i=!0,n=o,t++;break}}if(!i)break}return{index:t,parentMap:n}}_generateMap(e,t){let n,i=0,r=e;do{n={maps:[],parentMap:r,usedCount:1,value:t[i]},r.maps.unshift(n),r=n,i++}while(i<t.length);const o=n;return o.cacheKey=""+ ++this._lastId,o}_removeLeastUsedMap(e){if(!this._options.maxSize)return;const t=this._usedMaps.indexOf(e);if(this._usedMaps.splice(-1===t?0:t,-1===t?0:1,e),this._usedMaps.length<=this._options.maxSize)return;const n=this._usedMaps.pop();n&&(this._removeMap(n),this._options.onExpire(n.cacheKey))}_removeMap(e){e.parentMap&&(e.parentMap.maps.splice(e.parentMap.maps.indexOf(e),1),function(e){return Object.prototype.hasOwnProperty.call(e,"parentMap")}(e.parentMap)||this._removeMap(e.parentMap))}}function IS(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,function(e,t,n){if("function"!=typeof n.value)return n;let i=new SS,r=n.value,o=Pe(r);return Ln(e,t,{get(){const e=(...e)=>{const t=o.call(this,...e);if(1===i.getUsedCount(...e))return t;const n=r.call(this,...e);return Af(n,t,{keyFilter:e=>!function(e){return 0===`${e}`.indexOf("$$")||0===`${e}`.indexOf("_")}(e)})?t:(o.cache.set(i.getKey(...e),n),n)};return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=new SS,r=e,o=Pe(r)}})}(e.prototype,n,i))}),t}let wS=class{constructor(e){this._checkoutButton=e.checkoutButton}getInitializeButtonError(e){return this._checkoutButton.getInitializeError(e)}getDeinitializeButtonError(e){return this._checkoutButton.getDeinitializeError(e)}};wS=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([IS],wS);const CS=wS;let bS=class{constructor(e){this._checkoutButton=e.checkoutButton}isInitializingButton(e){return this._checkoutButton.isInitializing(e)}isDeinitializingButton(e){return this._checkoutButton.isDeinitializing(e)}};bS=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([IS],bS);const PS=bS;function OS(e){return{errors:new CS(e),statuses:new PS(e)}}let ES=class{constructor(e,t){this._store=e,this._buttonStrategyActionCreator=t,this._state=OS(this._store.getState()),this._store.subscribe(e=>{this._state=OS(e)})}getState(){return this._state}subscribe(e,...t){return this._store.subscribe(()=>e(this.getState()),e=>e.checkoutButton.getState(),...t.map(e=>t=>e(OS(t))))}initializeButton(e){const t=(n=e.containerId,/^\w[\w\-\:\.]*$/.test(n)?[e.containerId]:function(e,t){const n=document.querySelectorAll(e);if(!n.length)throw new Vt(`Unable to find any element with the specified selector: ${e}`);return Array.prototype.slice.call(n).map(e=>(e.id||(e.id=vS(t)),e.id))}(e.containerId,`${e.methodId}-container`));var n;return Promise.all(t.map(t=>{const n=this._buttonStrategyActionCreator.initialize(Object.assign(Object.assign({},e),{containerId:t})),i=`checkoutButtonStrategy:${e.methodId}:${t}`;return this._store.dispatch(n,{queueId:i})})).then(()=>this.getState())}deinitializeButton(e){const t=this._buttonStrategyActionCreator.deinitialize(e),n=`checkoutButtonStrategy:${e.methodId}`;return this._store.dispatch(t,{queueId:n}).then(()=>this.getState())}};ES=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],ES);const AS=ES;class TS{constructor(e,t,n){this._registry=e,this._registryV2=t,this._paymentMethodActionCreator=n}initialize(e){return t=>{const n={methodId:e.methodId,containerId:e.containerId};if(t.getState().checkoutButton.isInitialized(e.methodId,e.containerId))return v();const i=e.currencyCode?{params:{currencyCode:e.currencyCode}}:{},r=Object.assign(Object.assign({},i),{timeout:e.timeout,useCache:!0});return g(C(l(Yf.InitializeButtonRequested,void 0,n)),this._paymentMethodActionCreator.loadPaymentMethod(e.methodId,r)(t),f(()=>this._getStrategy(e.methodId).initialize(e).then(()=>l(Yf.InitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Ke(Yf.InitializeButtonFailed,e,n)))}}deinitialize(e){return t=>{const n={methodId:e.methodId};return t.getState().checkoutButton.isInitialized(e.methodId)?g(C(l(Yf.DeinitializeButtonRequested,void 0,n)),f(()=>this._getStrategy(e.methodId).deinitialize().then(()=>l(Yf.DeinitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Ke(Yf.DeinitializeButtonFailed,e,n))):v()}}_getStrategy(e){let t;try{t=this._registryV2.get({id:e})}catch(n){t=this._registry.get(e)}return t}}class kS extends rt{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"}}var DS,MS,zS,xS,NS,RS,FS,LS;class jS{constructor(e){this._scriptLoader=e,this._window=window}loadPaypal(e=""){return t=this,n=void 0,r=function*(){const t="//www.paypalobjects.com/api/checkout.min.js",n={async:!0,attributes:{"data-merchant-id":e}};if(e?yield this._scriptLoader.loadScript(t,n):yield this._scriptLoader.loadScript(t),!this._window.paypal)throw new kS;return this._window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(DS||(DS={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(MS||(MS={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(zS||(zS={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(xS||(xS={})),function(e){e.PILL="pill",e.RECT="rect"}(NS||(NS={}));class BS{constructor(e,t,n,i,r=""){this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=n,this._formPoster=i,this._host=r}initialize(e){const t=e.paypal,n=this._store.getState(),i=this._paymentMethod=n.paymentMethods.getPaymentMethod(e.methodId);if(!t)throw new Vt;if(!i)throw new ot(tt.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then(n=>{var r,o;if(!i||!i.config.merchantId)throw new ot(tt.MissingPaymentMethod);const a=i.config.merchantId,s=i.config.testMode?"sandbox":"production",d={[s]:t.clientId},c=n.FUNDING.CREDIT||"credit",l=t.allowCredit?[c]:[],u=t.allowCredit?[]:[c];return n.Button.render({env:s,client:d,commit:t.shouldProcessPayment,funding:{allowed:l,disallowed:u},style:Object.assign(Object.assign({shape:NS.RECT},pe(t.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(r=t.style)||void 0===r?void 0:r.size)?MS.RESPONSIVE:null===(o=t.style)||void 0===o?void 0:o.size}),payment:(e,n)=>this._setupPayment(a,n,t.onPaymentError),onAuthorize:(e,n)=>this._tokenizePayment(e,n,t.shouldProcessPayment,t.onAuthorizeError)},e.containerId)})}deinitialize(){return this._paymentMethod=void 0,Promise.resolve()}_setupPayment(e,t,n){if(!t)throw new gn(ln.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then(n=>{const i=n.cart.getCart(),r=i?i.id:"";return t.request.post(`${this._host}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:r},{headers:Object.assign({"X-API-INTERNAL":Tt},et)})}).then(e=>e.id).catch(e=>{throw n&&n(e),e})}_tokenizePayment(e,t,n,i){if(!this._paymentMethod)throw new gn(ln.CheckoutButtonNotInitialized);if(!t)throw new gn(ln.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new ot(tt.MissingPayment);const r=this._paymentMethod.id;return t.payment.get(e.paymentID).then(t=>{this._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})})}}function US(e){const{host:t}=null!=e?e:{},i=gS({config:{meta:{host:null==e?void 0:e.host,locale:null==e?void 0:e.locale},errors:{},statuses:{}}}),r=n({host:t}),o=Ee({host:t}),s=function(e){const t=new Ht;for(const[,n]of Object.entries({}))if(qt(n))for(const i of n.resolveIds)t.register(i,()=>n(e));return t}($g(i));return new AS(i,new TS(function(e,t,n,i){const r=new Gt,o=a(),s=new tn(t),d=new rn(s,new Pt(new kt(t)),new an(new sn(t)));return r.register(zy.PAYPALEXPRESS,()=>new BS(e,d,new jS(o),n,i)),r}(i,r,o,t),s,new Wm(new $m(r))))}!function(e){e.CheckoutComplete="CHECKOUT_COMPLETE",e.CheckoutError="CHECKOUT_ERROR",e.CheckoutLoaded="CHECKOUT_LOADED",e.FrameError="FRAME_ERROR",e.FrameLoaded="FRAME_LOADED",e.SignedOut="SIGNED_OUT"}(RS||(RS={}));class qS extends Et{constructor(e){super(e,{message:e.body.title}),this.name="InvalidLoginTokenError",this.type="invalid_login_token"}}!function(e){e.MissingContainer="missing_container",e.MissingContent="missing_content",e.UnknownError="unknown_error"}(FS||(FS={}));class VS extends rt{constructor(e,t=FS.UnknownError){super(e||"Unable to embed the checkout form."),this.subtype=t,this.name="NotEmbeddableError",this.type="not_embeddable"}}!function(e){e.StyleConfigured="STYLE_CONFIGURED"}(LS||(LS={}));const GS="isCookieAllowed",HS="lastAllowCookieAttempt";let WS=class{constructor(e,t,n,i,r,o,a,s){this._iframeCreator=e,this._messageListener=t,this._messagePoster=n,this._loadingIndicator=i,this._requestSender=r,this._storage=o,this._location=a,this._options=s,this._isAttached=!1,this._options.onComplete&&this._messageListener.addListener(RS.CheckoutComplete,this._options.onComplete),this._options.onError&&this._messageListener.addListener(RS.CheckoutError,this._options.onError),this._options.onLoad&&this._messageListener.addListener(RS.CheckoutLoaded,this._options.onLoad),this._options.onFrameLoad&&this._messageListener.addListener(RS.FrameLoaded,this._options.onFrameLoad),this._options.onSignOut&&this._messageListener.addListener(RS.SignedOut,this._options.onSignOut),this._messageListener.addListener(RS.FrameLoaded,()=>this._configureStyles())}attach(){return this._isAttached?Promise.resolve(this):(this._isAttached=!0,this._messageListener.listen(),this._loadingIndicator.show(this._options.containerId),this._allowCookie().then(()=>this._attemptLogin()).then(e=>this._iframeCreator.createFrame(e,this._options.containerId)).then(e=>{this._iframe=e,this._configureStyles(),this._loadingIndicator.hide()}).catch(e=>(this._isAttached=!1,this._retryAllowCookie(e).catch(()=>{throw this._messageListener.trigger({type:RS.FrameError,payload:e}),this._loadingIndicator.hide(),e}))).then(()=>this))}detach(){this._isAttached&&(this._isAttached=!1,this._messageListener.stopListen(),this._iframe&&this._iframe.parentNode&&(this._iframe.parentNode.removeChild(this._iframe),this._iframe.iFrameResizer.close()))}_configureStyles(){this._iframe&&this._iframe.contentWindow&&this._options.styles&&(this._messagePoster.setTarget(this._iframe.contentWindow),this._messagePoster.post({type:LS.StyleConfigured,payload:this._options.styles}))}_attemptLogin(){return/^\/login\/token/.test(Cn(this._options.url).pathname)?this._requestSender.post(this._options.url).then(({body:{redirectUrl:e}})=>e).catch(e=>Promise.reject(new qS(e))):Promise.resolve(this._options.url)}_allowCookie(){if(this._storage.getItem(GS))return Promise.resolve();this._storage.setItem(GS,!0),this._storage.setItem(HS,Date.now());const{origin:e}=Cn(this._options.url),t=`${e}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(this._location.href)}`;return document.body.style.visibility="hidden",this._location.replace(t),new Promise(()=>{})}_retryAllowCookie(e){const t=Number(this._storage.getItem(HS));return(!t||Date.now()-t>6e5)&&e instanceof VS&&e.subtype===FS.MissingContent?(this._storage.removeItem(HS),this._storage.removeItem(GS),this._allowCookie()):Promise.reject()}};WS=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],WS);const $S=WS;class YS{constructor(e){this._options=e}createFrame(e,t){const n=document.getElementById(t),{timeout:i=6e4}=this._options||{};if(!n)throw new VS("Unable to embed the iframe because the container element could not be found.",FS.MissingContainer);const r=document.createElement("iframe");return r.src=e,r.style.border="none",r.style.display="none",r.style.width="100%",r.allowPaymentRequest=!0,r.allow="payment",n.appendChild(r),this._toResizableFrame(r,i).catch(e=>{throw n.removeChild(r),e})}_toResizableFrame(e,t){return new Promise((n,i)=>{const r=window.setTimeout(()=>{i(new VS("Unable to embed the iframe because the content could not be loaded."))},t),o=t=>{if((t.origin===Cn(e.src).origin||t.origin===$n(Cn(e.src)).origin)&&(Pn(t.data,RS.FrameError)&&(a(),i(new VS(t.data.payload.message,FS.MissingContent))),Pn(t.data,RS.FrameLoaded))){e.style.display="";const i=Mn({scrolling:!1,sizeWidth:!1,heightCalculationMethod:t.data.payload&&t.data.payload.contentId?"taggedElement":"lowestElement"},e);a(),n(i[i.length-1])}},a=()=>{window.removeEventListener("message",o),window.clearTimeout(r)};window.addEventListener("message",o)})}}function KS(e){const t=Cn(e.url).origin;return new $S(new YS,new Kn(t),new On(t),new fd({styles:e.styles&&e.styles.loadingIndicator}),n(),new iy("BigCommerce.EmbeddedCheckout"),window.location,e).attach()}function JS(e){if(!e.payload||!e.payload.contentId)return;const t=document.getElementById(e.payload.contentId);t&&!t.hasAttribute("data-iframe-height")&&t.setAttribute("data-iframe-height","")}function ZS(e){return"object"==typeof e&&null!==e&&"message"in e&&"type"in e}let QS=class{constructor(e,t,n,i={}){this._messageListener=e,this._messagePoster=t,this._untargetedMessagePoster=n,this._messageHandlers=i,this._messageListener.listen()}postComplete(){const e={type:RS.CheckoutComplete};this._postMessage(e)}postError(e){const t={type:RS.CheckoutError,payload:this._transformError(e)};this._postMessage(t)}postFrameError(e){const t={type:RS.FrameError,payload:this._transformError(e)};this._postMessage(t,{untargeted:!0})}postFrameLoaded(e){const t={type:RS.FrameLoaded,payload:e};this._postMessage(t)}postLoaded(){const e={type:RS.CheckoutLoaded};this._postMessage(e)}postSignedOut(){const e={type:RS.SignedOut};this._postMessage(e)}receiveStyles(e){this._messageListener.addListener(LS.StyleConfigured,({payload:t})=>{e(t)})}_postMessage(e,t){if(this._notifyMessageHandlers(e),t&&t.untargeted)return this._untargetedMessagePoster.post(e);this._messagePoster.post(e)}_notifyMessageHandlers(e){Object.keys(this._messageHandlers).forEach(t=>{if(e.type!==t)return;const n=this._messageHandlers[t];n&&n.call(null,e)})}_transformError(e){return{message:e.message,type:ZS(e)?e.type:void 0,subtype:ZS(e)?e.subtype:void 0}}};QS=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],QS);const XS=QS;let eI=class{postComplete(){}postError(){}postFrameError(){}postFrameLoaded(){}postLoaded(){}postSignedOut(){}receiveStyles(){}};eI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],eI);const tI=eI;function nI(e){Ve(939);const t=e.parentWindow||window.parent;return window===t?new tI:new XS(new Kn(e.parentOrigin),new On(e.parentOrigin,t),new On("*",t),{[RS.FrameLoaded]:JS})}const iI="en",rI="optimized_checkout";let oI=class{constructor(e,t){this._logger=t;const{locale:n,locales:i,translations:r}=this._transformConfig(e);this._locale=n,this._locales=i,this._translations=r,this._formatters={}}mapKeys(e){Object.keys(e).forEach(t=>{const n=`${rI}.${e[t]}`;this._translations[`${rI}.${t}`]=this._translations[n]})}getLocale(){return this._hasTranslations()?this._locale:iI}translate(e,t={}){var n;const i=`${rI}.${e}`;if("string"!=typeof this._translations[i])return this._logger.warn(`Translation key "${i}" is missing`),i;this._formatters[i]||(this._formatters[i]=new Be(this._escapeSpecialCharacters(this._translations[i]||""),this._locales[i],void 0,{ignoreTag:!0}));try{return this._formatters[i].format(this._transformData(t))}catch(e){if(this._isFormatError(e))return null!==(n=e.originalMessage)&&void 0!==n?n:"";throw e}}_transformConfig(e={}){const t={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:e.locale||iI},n=e.locales||{},i=this._flattenObject(e.translations||{}),r=this._flattenObject(e.defaultTranslations||{}),o=this._flattenObject(e.fallbackTranslations||{});return Se(Object.keys(o),Object.keys(r),Object.keys(i)).forEach(a=>{var s,d;i&&i[a]?(t.translations[a]=i[a],t.locales[a]=n[a]||t.locale):r[a]?(t.translations[a]=r[a],t.locales[a]=null!==(s=e.defaultLocale)&&void 0!==s?s:iI):(t.translations[a]=o[a],t.locales[a]=null!==(d=e.fallbackLocale)&&void 0!==d?d:iI)}),t}_flattenObject(e,t={},n=""){try{Object.keys(e).forEach(i=>{const r=e[i],o=n?`${n}.${i}`:i;if(Z(r))return this._flattenObject(r,t,o);t[o]=r})}catch(e){this._logger.warn(`Unable to parse object: ${e}`)}return t}_transformData(e){return Object.keys(e).reduce((t,n)=>{const i=e[n];return t[n]=null==i?"":i,t},{})}_hasTranslations(){return Object.keys(this._locales).map(e=>this._locales[e]).filter(e=>e.split("-")[0]===this._locale.split("-")[0]).length>0}_isFormatError(e){return"object"==typeof e&&null!==e&&"originalMessage"in e}_escapeSpecialCharacters(e){return e.replace(/(\w+)='([^']*)'/g,"$1=''$2''")}};oI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],oI);const aI=oI;function sI(e={}){return new aI(e,wt())}let dI=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};dI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],dI);const cI=dI;function lI(e){return new cI(e)}function uI(e){return e&&"ga"in e&&"function"==typeof e.ga}function hI(e,t){uI(window)&&window.ga("send",e,Object.assign(Object.assign({},t),{nonInteraction:!1}))}function pI(e){return mI(e).length>=8096}function mI(e){return Object.keys(e).reduce((t,n)=>{const i=typeof e[n];return"string"===i||"number"===i?[...t,`${n}=${e[n]}`]:"object"===i&&null!==e[n]?[...t,mI(e[n])]:t},[]).join("&")}var yI;!function(e){e[e.CUSTOMER=1]="CUSTOMER",e[e.SHIPPING=2]="SHIPPING",e[e.BILLING=3]="BILLING",e[e.PAYMENT=4]="PAYMENT"}(yI||(yI={}));const gI={customer:yI.CUSTOMER,shipping:yI.SHIPPING,billing:yI.BILLING,payment:yI.PAYMENT};class fI{constructor(e,t,n,{checkoutSteps:i}={}){if(this.checkoutService=e,this.analyticsExtraItemsManager=t,this.analytics=n,this._checkoutStarted=!1,this._completedSteps={},this._viewedSteps={},this._analyticStepOrder=["customer","shipping","billing","payment"],void 0!==i){if(i.some(e=>!(e in gI)))throw new Vt(`Invalid checkout steps provided. Valid values are: ${ie(gI).join(", ")}.`);this._analyticStepOrder=i}}trackCheckoutStarted(){if(this._checkoutStarted)return;const e=this.getCheckout();if(!e)return;const{coupons:t,grandTotal:n,shippingCostTotal:i,taxTotal:r,cart:{lineItems:o,discountAmount:a,id:s}}=e,d=this.analyticsExtraItemsManager.saveExtraItemsData(s,o);this.analytics.track("Checkout Started",this.getTrackingPayload({revenue:n,shipping:i,tax:r,discount:a,coupons:t,lineItems:o,extraItemsData:d})),this._checkoutStarted=!0}trackOrderComplete(){var e;const t=this.getOrder();if(!t)return;const{isComplete:n,orderId:i,orderAmount:r,shippingCostTotal:o,taxTotal:a,discountAmount:s,coupons:d,lineItems:c,cartId:l}=t;if(!n)return;const u=this.analyticsExtraItemsManager.readExtraItemsData(l);if(null===u)return;const h=null===(e=this.checkoutService.getState().data.getConfig())||void 0===e?void 0:e.checkoutSettings.features["DATA-6891.missing_orders_within_GA"],p=this.getTrackingPayload({orderId:i,revenue:r,shipping:o,tax:a,discount:s,coupons:d,extraItemsData:u,lineItems:c});if(h&&pl(window)&&uI(window)&&pI(p))return hI("transaction",{"&ti":p.order_id,"&ta":p.affiliation,"&tr":p.revenue,"&ts":p.shipping,"&tt":p.tax,"&tcc":p.coupon,"&cu":p.currency}),p.products.forEach(e=>{hI("item",{"&ti":p.order_id,"&in":e.name,"&ic":e.sku,"&iv":`${e.category}`,"&ip":e.price,"&iq":e.quantity})}),this.analyticsExtraItemsManager.clearExtraItemData(l);this.analytics.track("Order Completed",p),this.analyticsExtraItemsManager.clearExtraItemData(l)}trackStepViewed(e){const t=this.getIdFromStep(e);t&&!this.hasStepViewed(t)&&(this.trackViewed(t),this.backfill(t))}trackStepCompleted(e){const t=this.getIdFromStep(e);t&&!this.hasStepCompleted(t)&&(this.backfill(t),this.trackCompleted(t))}backfill(e){for(const t of this._analyticStepOrder){const n=this.getIdFromStep(t);if(!n)break;if(this.hasStepViewed(n)||this.trackViewed(n),n===e)break;this.hasStepCompleted(n)||this.trackCompleted(n)}}trackCompleted(e){const t=this.getSelectedShippingOption(),{code:n=""}=this.getShopperCurrency()||{},i=this.getPaymentMethodName(),r={step:e,currency:n};t&&(r.shipping_method=t.description),i&&(r.payment_method=i),r.shipping_method||r.payment_method||(r.shipping_method=" "),this.analytics.track("Checkout Step Completed",r);const o=t?t.id:"",a=e===yI.SHIPPING?`${e}-${o}`:e;this._completedSteps[a]=!0}getTrackingPayload({orderId:e,revenue:t,shipping:n,tax:i,discount:r,coupons:o,extraItemsData:a,lineItems:s}){const{code:d=""}=this.getShopperCurrency()||{},{storeName:c=""}=this.getStoreProfile()||{};return{order_id:String(e),affiliation:c,revenue:this.toShopperCurrency(t),shipping:this.toShopperCurrency(n),tax:this.toShopperCurrency(i),discount:this.toShopperCurrency(r),coupon:(o||[]).map(e=>e.code.toUpperCase()).join(","),currency:d,products:this.getProducts(a,s)}}hasStepCompleted(e){const t=this.getSelectedShippingOption(),n=t?t.id:"";return Object.prototype.hasOwnProperty.call(this._completedSteps,e)||e===yI.SHIPPING&&Object.prototype.hasOwnProperty.call(this._completedSteps,`${e}-${n}`)}hasStepViewed(e){return!!this._viewedSteps[e]}getIdFromStep(e){const t=e.split(".");return gI[t[0]]||null}trackViewed(e){const t=this.getShopperCurrency();this.analytics.track("Checkout Step Viewed",{step:e,currency:t?t.code:""}),this._viewedSteps[e]=!0}getOrder(){const{data:{getOrder:e}}=this.checkoutService.getState();return e()}getCheckout(){const{data:{getCheckout:e}}=this.checkoutService.getState();return e()}getShopperCurrency(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.shopperCurrency}getStoreProfile(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.storeProfile}toShopperCurrency(e){const{exchangeRate:t=1}=this.getShopperCurrency()||{};return Math.round(e*t*100)/100}getSelectedShippingOption(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedShippingOption();return t&&t.id&&t.description?t:null}getPaymentMethodName(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedPaymentMethod();return t&&t.config&&t.config.displayName||""}getProducts(e,t){const n=(t.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,price:e.listPrice,quantity:e.quantity,name:e.name})),i=t.giftCertificates.map(e=>({product_id:e.id,price:this.toShopperCurrency(e.amount),name:e.name,quantity:1}));return[...n,...[...t.physicalItems,...t.digitalItems].map(t=>{let n;t.options&&t.options.length&&(n=t.options.map(e=>`${e.name}:${e.value}`),n.sort());const i=Array.isArray(n)&&n.length?n.join(", "):"single-product-option",r=e[t.productId]&&e[t.productId].brand;return Object.assign({product_id:String(t.productId),sku:t.sku,price:t.salePrice,image_url:t.imageUrl,name:t.name,quantity:t.quantity,category:e[t.productId]?e[t.productId].category:"",variant:i},r&&{brand:r})}),...i]}}class vI{trackCheckoutStarted(){}trackOrderComplete(){}trackStepViewed(){}trackStepCompleted(){}}function _I(e,t){const{data:n}=e.getState(),i=n.getConfig();if(!i)throw new ot(tt.MissingCheckoutConfig);const{isAnalyticsEnabled:r}=i.checkoutSettings;return r&&pl(window)?new fI(e,new hl(Te),window.analytics,t):new vI}function SI(e){return Boolean(e.hasOwnProperty("braintreeFastlane"))}class II{constructor(e){this.checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this.checkoutService.getState(),t=e.data.getPaymentMethod("braintree")||e.data.getPaymentMethod("braintreeacceleratedcheckout"),n=null==t?void 0:t.initializationData.isBraintreeAnalyticsV2Enabled,i=SI(window)&&window.braintreeFastlane.events;return n&&i}_getBraintreeEventsOrThrow(){if(SI(window))return window.braintreeFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getBraintreeEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getBraintreeEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getBraintreeEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this.checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a=n.data.getPaymentMethod("braintreeacceleratedcheckout"),s=[{treatment_group:!n.errors.getLoadPaymentMethodError("braintreeacceleratedcheckout")&&(null==a?void 0:a.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id)||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(s)}}_getEmailSubmittedEventOptions(){const e=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this.checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function wI(e){return new II(e)}class CI{constructor(e){this._checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this._checkoutService.getState().data.getPaymentMethod("paypalcommerce"),t=((null==e?void 0:e.initializationData)||{}).isPayPalCommerceAnalyticsV2Enabled,n=window,i=!!n.paypalFastlane&&!!n.paypalFastlane.events;return t&&i}_getPayPalEventsOrThrow(){const e=window;if(e.paypalFastlane&&e.paypalFastlane.events)return e.paypalFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getPayPalEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getPayPalEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getPayPalEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this._checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a="paypalcommerceacceleratedcheckout",s=n.data.getPaymentMethod(a),d=[{treatment_group:!n.errors.getLoadPaymentMethodError(a)&&(null==s?void 0:s.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id.replace(/-/g,""))||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(d)}}_getEmailSubmittedEventOptions(){const e=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this._checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function bI(e){return new CI(e)}var PI;class OI{constructor(e,t){this._host=e,this._hostedFormFactory=t}submitStoredCard(e,t){return n=this,i=void 0,o=function*(){const n=this._hostedForm;if(!n)throw new gn(ln.PaymentNotInitialized);yield n.validate().then(()=>n.submitStoredCard({fields:e,data:t}))},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}function EI(e){const t=gS();return new OI(e,new wy(t))}!function(e){e.CUSTOMER="customer",e.SHIPPING="shipping",e.BILLING="billing",e.PAYMENT="payment"}(PI||(PI={}));const AI=[PI.CUSTOMER,PI.SHIPPING,PI.BILLING,PI.PAYMENT];class TI{constructor(e,t){this.subscribe=e,this.bodlEvents=t,this._checkoutStarted=!1,this._emailEntryBegan=!1,this._shippingOptionsShown=!1,this._completedSteps={},this.subscribe(e=>{var t;if(this.setState(e.data),!(null===(t=this.state)||void 0===t?void 0:t.getConfig()))throw new ot(tt.MissingCheckoutConfig)})}setState(e){this.state=e}checkoutBegin(){const e=this._getCommonCheckoutData();!this._checkoutStarted&&e&&(this.bodlEvents.emitCheckoutBeginEvent(e),this._checkoutStarted=!0)}orderPurchased(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getOrder();if(!t)return;const{currency:n,isComplete:i,orderId:r,orderAmount:o,shippingCostTotal:a,lineItems:s,cartId:d,coupons:c,channelId:l,taxTotal:u}=t;i&&this.bodlEvents.emitOrderPurchasedEvent({event_id:d,currency:n.code,order_id:r,tax:u,channel_id:l,cart_value:o,coupon_codes:c.map(e=>e.code.toUpperCase()),shipping_cost:a,line_items:this._getProducts(s,n.code)})}stepCompleted(e){e&&AI.some(t=>(this._hasStepCompleted(t)||this._trackCompletedStep(t),t===e))}customerEmailEntry(e){!this._emailEntryBegan&&(null==e?void 0:e.length)&&(this._emailEntryBegan=!0,this.bodlEvents.emit("bodl_checkout_email_entry_began"))}customerSuggestionInit(e){this.bodlEvents.emit("bodl_checkout_customer_suggestion_initialization",e)}customerSuggestionExecute(){this.bodlEvents.emit("bodl_checkout_customer_suggestion_execute")}customerPaymentMethodExecuted(e){this.bodlEvents.emit("bodl_checkout_customer_payment_method_executed",e)}showShippingMethods(){this._shippingOptionsShown||(this._shippingOptionsShown=!0,this.bodlEvents.emit("bodl_checkout_show_shipping_options"))}selectedPaymentMethod(e){const t=this._getCommonCheckoutData();t&&e&&this.bodlEvents.emitPaymentDetailsProvidedEvent(Object.assign(Object.assign({},t),{payment_type:e}))}clickPayButton(e){this.bodlEvents.emit("bodl_checkout_click_pay_button",e)}paymentRejected(){this.bodlEvents.emit("bodl_checkout_payment_rejected")}paymentComplete(){this.bodlEvents.emit("bodl_checkout_payment_complete")}exitCheckout(){this.bodlEvents.emit("bodl_checkout_exit")}_trackCompletedStep(e){this._completedSteps[e]=!0;const t={[PI.SHIPPING]:this._trackShippingStepCompleted.bind(this)}[e];t?t():this.bodlEvents.emit("bodl_checkout_step_completed",{step:e})}_trackShippingStepCompleted(){var e,t;const n=null===(t=null===(e=this.state)||void 0===e?void 0:e.getSelectedShippingOption())||void 0===t?void 0:t.description,i=this._getCommonCheckoutData();i&&n&&this.bodlEvents.emitShippingDetailsProvidedEvent(Object.assign(Object.assign({},i),{shipping_method:n}))}_getCommonCheckoutData(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getCheckout();if(!t)return null;const{cart:{cartAmount:n,currency:i,lineItems:r,id:o,coupons:a},channelId:s}=t;return{event_id:o,currency:i.code,cart_value:n,coupon_codes:a.map(e=>e.code.toUpperCase()),line_items:this._getProducts(r,i.code),channel_id:s}}_getProducts(e,t){const n=(e.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,base_price:e.listPrice,sale_price:e.listPrice,purchase_price:e.listPrice,quantity:e.quantity,product_name:e.name,currency:t})),i=e.giftCertificates.map(e=>({product_id:e.id,gift_certificate_id:e.id,base_price:e.amount,sale_price:e.amount,purchase_price:e.amount,product_name:e.name,gift_certificate_name:e.name,gift_certificate_theme:e.theme,quantity:1,currency:t}));return[...n,...[...e.physicalItems,...e.digitalItems].map(e=>{let n;return e.options&&e.options.length&&(n=e.options.map(e=>`${e.name}:${e.value}`),n.sort()),{product_id:e.productId,quantity:e.quantity,product_name:e.name,base_price:e.listPrice,sale_price:e.salePrice,purchase_price:e.salePrice>0?e.salePrice:e.listPrice,sku:e.sku,variant_id:e.variantId,discount:e.discountAmount,coupon_amount:e.couponAmount,brand_name:e.brand,currency:t,category_names:(i=e,Array.isArray(i.categoryNames)?i.categoryNames:Array.isArray(i.categories)?q(i.categories).map(({name:e})=>e):[]),retail_price:e.retailPrice};var i}),...i].map(e=>Object.assign(Object.assign({},e),{product_id:String(e.product_id)}))}_hasStepCompleted(e){return this._completedSteps[e]}}class kI{checkoutBegin(){}orderPurchased(){}stepCompleted(){}customerEmailEntry(){}customerSuggestionInit(){}customerSuggestionExecute(){}customerPaymentMethodExecuted(){}showShippingMethods(){}selectedPaymentMethod(){}clickPayButton(){}paymentRejected(){}paymentComplete(){}exitCheckout(){}}function DI(e){return function(e){return"bodlEvents"in e}(window)?new TI(e,window.bodlEvents.checkout):new kI}export{Bn as ExtensionCommandType,Un as ExtensionQueryType,DI as createBodlService,wI as createBraintreeAnalyticTracker,US as createCheckoutButtonInitializer,fS as createCheckoutService,lI as createCurrencyService,nI as createEmbeddedCheckoutMessenger,sI as createLanguageService,bI as createPayPalCommerceAnalyticTracker,_I as createStepTracker,EI as createStoredCardHostedFormService,i as createTimeout,KS as embedCheckout,$e as isExtraField};
|
|
1
|
+
import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{createRequestSender as n,createTimeout as i}from"@bigcommerce/request-sender";import{ScriptLoader as r,createScriptLoader as o,getScriptLoader as a,getStylesheetLoader as s}from"@bigcommerce/script-loader";import{combineReducers as d,composeReducers as c,createAction as l,createDataStore as u,createErrorAction as h,deepFreeze as p}from"@bigcommerce/data-store";import{Observable as m,Subject as y,concat as g,defer as f,empty as v,from as _,fromEvent as S,merge as I,noop as w,of as C,throwError as b}from"rxjs";import{catchError as P,delay as O,distinctUntilChanged as E,filter as A,map as T,retryWhen as k,shareReplay as D,switchMap as M,take as z}from"rxjs/operators";import{cond as x,constant as N,difference as R,each as F,filter as L,find as j,findIndex as B,flatMap as U,flatten as q,get as V,identity as G,includes as H,isArray as W,isEmpty as $,isEqual as Y,isMatch as K,isNil as J,isObject as Z,isPlainObject as Q,isString as X,isUndefined as ee,kebabCase as te,keyBy as ne,keys as ie,last as re,map as oe,max as ae,memoize as se,merge as de,noop as ce,omit as le,omitBy as ue,overSome as he,pick as pe,pickBy as me,reduce as ye,round as ge,some as fe,stubTrue as ve,transform as _e,union as Se,uniq as Ie,uniqueId as we,values as Ce,without as be}from"lodash";import{memoize as Pe,memoizeOne as Oe}from"@bigcommerce/memoize";import{createFormPoster as Ee}from"@bigcommerce/form-poster";import{supportsPopups as Ae}from"@braintree/browser-detection";import{default as Te}from"local-storage-fallback";import{createClient as ke}from"@bigcommerce/bigpay-client";import{creditCardType as De,number as Me}from"card-validator";import{exclude as ze,parseUrl as xe,stringifyUrl as Ne}from"query-string";import{createSelector as Re,createSelectorCreator as Fe,defaultMemoize as Le}from"reselect";import{default as je}from"shallowequal";import{IntlMessageFormat as Be}from"intl-messageformat";var Ue={785:t=>{t.exports=e},939:e=>{e.exports=t}},qe={};function Ve(e){var t=qe[e];if(void 0!==t)return t.exports;var n=qe[e]={exports:{}};return Ue[e](n,n.exports,Ve),n.exports}Ve.d=(e,t)=>{for(var n in t)Ve.o(t,n)&&!Ve.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},Ve.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ve.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var Ge={};Ve.r(Ge),Ve.d(Ge,{createAmazonPayV2CustomerStrategy:()=>wi,createApplePayCustomerStrategy:()=>Xi,createBigCommercePaymentsCustomerStrategy:()=>br,createBigCommercePaymentsFastlaneCustomerStrategy:()=>Hr,createBigCommercePaymentsPayLaterCustomerStrategy:()=>Yr,createBigCommercePaymentsVenmoCustomerStrategy:()=>Zr,createBoltCustomerStrategy:()=>so,createBraintreeFastlaneCustomerStrategy:()=>zo,createBraintreePaypalCreditCustomerStrategy:()=>Oo,createBraintreePaypalCustomerStrategy:()=>Co,createBraintreeVisaCheckoutCustomerStrategy:()=>Ro,createGooglePayAdyenV2CustomerStrategy:()=>ca,createGooglePayAdyenV3CustomerStrategy:()=>la,createGooglePayAuthorizeDotNetCustomerStrategy:()=>ha,createGooglePayBigCommercePaymentsCustomerStrategy:()=>as,createGooglePayBnzCustomerStrategy:()=>Sa,createGooglePayBraintreeCustomerStrategy:()=>Ya,createGooglePayCheckoutComCustomerStrategy:()=>fa,createGooglePayCybersourceCustomerStrategy:()=>_a,createGooglePayOrbitalCustomerStrategy:()=>wa,createGooglePayPayPalCommerceCustomerStrategy:()=>is,createGooglePayStripeCustomerStrategy:()=>qa,createGooglePayStripeUpeCustomerStrategy:()=>Va,createGooglePayTdOnlineMartCustomerStrategy:()=>ls,createGooglePayWorldpayAccessCustomerStrategy:()=>Ha,createPayPalCommerceCreditCustomerStrategy:()=>Js,createPayPalCommerceCustomerStrategy:()=>zs,createPayPalCommerceFastlaneCustomerStrategy:()=>sd,createPayPalCommerceVenmoCustomerStrategy:()=>Xs,createStripeLinkV2CustomerStrategy:()=>wd,createStripeUPECustomerStrategy:()=>ud});var He={};Ve.r(He),Ve.d(He,{createAdyenV2PaymentStrategy:()=>Ld,createAdyenV3PaymentStrategy:()=>Vd,createAffirmPaymentStrategy:()=>Yd,createAfterpayPaymentStrategy:()=>tc,createAmazonPayV2PaymentStrategy:()=>rc,createApplePayPaymentStrategy:()=>dc,createBigCommercePaymentsAlternativeMethodsPaymentStrategy:()=>Nc,createBigCommercePaymentsCreditCardsPaymentStrategy:()=>Mc,createBigCommercePaymentsFastlanePaymentStrategy:()=>vc,createBigCommercePaymentsPayLaterPaymentStrategy:()=>Ic,createBigCommercePaymentsPaymentStrategy:()=>mc,createBigCommercePaymentsRatePayPayPaymentStrategy:()=>Pc,createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy:()=>Fc,createBigCommercePaymentsVenmoPaymentStrategy:()=>Bc,createBlueSnapDirectAPMPaymentStrategy:()=>al,createBlueSnapDirectCreditCardPaymentStrategy:()=>rl,createBlueSnapV2PaymentStrategy:()=>ul,createBoltPaymentStrategy:()=>vl,createBraintreeAchPaymentStrategy:()=>wl,createBraintreeCreditCardPaymentStrategy:()=>Ql,createBraintreeFastlanePaymentStrategy:()=>Ll,createBraintreeLocalMethodsPaymentStrategy:()=>xl,createBraintreePaypalPaymentStrategy:()=>kl,createBraintreeVenmoPaymentStrategy:()=>Gl,createBraintreeVisaCheckoutPaymentStrategy:()=>Ul,createCBAMPGSPaymentStrategy:()=>ou,createCheckoutComAPMPaymentStrategy:()=>Iu,createCheckoutComCreditCardPaymentStrategy:()=>mu,createCheckoutComFawryPaymentStrategy:()=>cu,createCheckoutComIdealPaymentStrategy:()=>vu,createCheckoutComSepaPaymentStrategy:()=>gu,createClearpayPaymentStrategy:()=>Pu,createCreditCardPaymentStrategy:()=>Ou,createCyberSourcePaymentStrategy:()=>Uu,createCyberSourceV2PaymentStrategy:()=>Wu,createGooglePayAdyenV2PaymentStrategy:()=>Qu,createGooglePayAdyenV3PaymentStrategy:()=>th,createGooglePayAuthorizeNetPaymentStrategy:()=>nh,createGooglePayBigCommercePaymentsPaymentStrategy:()=>vh,createGooglePayBraintreePaymentStrategy:()=>dh,createGooglePayCheckoutComPaymentStrategy:()=>ih,createGooglePayCybersourcePaymentStrategy:()=>rh,createGooglePayOrbitalPaymentStrategy:()=>oh,createGooglePayPPCPPaymentStrategy:()=>ph,createGooglePayStripePaymentStrategy:()=>ah,createGooglePayTdOnlineMartPaymentStrategy:()=>_h,createGooglePayWorldpayAccessPaymentStrategy:()=>sh,createHummPaymentStrategy:()=>wh,createKlarnaPaymentStrategy:()=>Ah,createKlarnaV2PaymentStrategy:()=>zh,createLegacyPaymentStrategy:()=>Nh,createMolliePaymentStrategy:()=>Uh,createMonerisPaymentStrategy:()=>Hh,createNoPaymentStrategy:()=>Pd,createOfflinePaymentStrategy:()=>$h,createOffsitePaymentStrategy:()=>Jh,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>lp,createPayPalCommerceCreditCardsPaymentStrategy:()=>pp,createPayPalCommerceCreditPaymentStrategy:()=>ip,createPayPalCommerceFastlanePaymentStrategy:()=>Sp,createPayPalCommercePaymentStrategy:()=>ep,createPayPalCommerceRatePayPaymentStrategy:()=>gp,createPayPalCommerceVenmoPaymentStrategy:()=>ap,createPayPalProPaymentStrategy:()=>zp,createPaypalExpressPaymentStrategy:()=>kp,createSagePayPaymentStrategy:()=>Np,createSezzlePaymentStrategy:()=>Lp,createSquareV2PaymentStrategy:()=>Wp,createStripeCSPaymentStrategy:()=>ym,createStripeOCSPaymentStrategy:()=>hm,createStripeUPEPaymentStrategy:()=>dm,createStripeV3PaymentStrategy:()=>im,createTDOnlineMartPaymentStrategy:()=>Sm,createWorldpayAccessOpenBankingPaymentStrategy:()=>Em,createWorldpayAccessPaymentStrategy:()=>Pm,createZipPaymentStrategy:()=>km});const We="b2bExtraField_";function $e(e){return e.name.startsWith(We)}function Ye(e){var t;const{fieldType:n,type:i}=function(e){switch(e){case"multiline_text":return{fieldType:"multiline",type:"string"};case"number":return{fieldType:"text",type:"integer"};case"dropdown":return{fieldType:"dropdown",type:"array"};default:return{fieldType:"text",type:"string"}}}(e.type);let r;return e.config.numberOfRows&&(r={rows:e.config.numberOfRows}),(null===(t=e.config.options)||void 0===t?void 0:t.length)&&(r=Object.assign(Object.assign({},r),{items:e.config.options.map(e=>({value:e,label:e}))})),{id:`${We}${e.id}`,name:`${We}${e.id}`,custom:!1,label:e.name,hidden:!e.visibleToStorefront,required:e.isRequired,default:null!=e.config.defaultValue?String(e.config.defaultValue):void 0,fieldType:n,type:i,maxLength:e.config.maxLength,max:e.config.maxValue,options:r}}function Ke(e,t,n){return(i=t)&&i.type&&i.error?g(C(t),b(h(e,t.payload,n))):b(h(e,t,n));var i}var Je;!function(e){e.LoadB2BTokenRequested="LOAD_B2B_TOKEN_REQUESTED",e.LoadB2BTokenSucceeded="LOAD_B2B_TOKEN_SUCCEEDED",e.LoadB2BTokenFailed="LOAD_B2B_TOKEN_FAILED"}(Je||(Je={}));const Ze="",Qe="";class Xe{constructor(e){this._requestSender=e}loadB2BToken(e){return t=>{var n;const i=t.getState(),{storeHash:r}=i.config.getStoreConfigOrThrow().storeProfile,{b2bBaseUrl:o=Ze,b2bClientId:a=Qe}=null!==(n=i.config.getStoreConfigOrThrow().checkoutSettings.b2bServiceDetails)&&void 0!==n?n:{},{id:s}=i.customer.getCustomerOrThrow(),{channelId:d}=i.checkout.getCheckoutOrThrow();return g(C(l(Je.LoadB2BTokenRequested)),f(()=>{return t=this,n=void 0,c=function*(){const{body:t}=yield this._requestSender.getB2BToken(a,s,r,d,o,e);return l(Je.LoadB2BTokenSucceeded,{token:t.data.token})},new((i=void 0)||(i=Promise))(function(e,r){function o(e){try{s(c.next(e))}catch(e){r(e)}}function a(e){try{s(c.throw(e))}catch(e){r(e)}}function s(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(o,a)}s((c=c.apply(t,n||[])).next())});var t,n,i,c})).pipe(P(e=>Ke(Je.LoadB2BTokenFailed,e)))}}}const et={"X-Checkout-SDK-Version":"1.904.2"};var tt,nt;class it{constructor(e){this._requestSender=e}getB2BToken(e,t,n,i,r,o){return a=this,s=void 0,c=function*(){const{body:a}=yield this._requestSender.get("/customer/current.jwt",{timeout:null==o?void 0:o.timeout,params:{app_client_id:e},headers:et});return this._requestSender.post(`${r}/api/v2/login`,{timeout:null==o?void 0:o.timeout,credentials:!1,headers:{"Content-Type":"application/json"},body:{bcToken:a.token,customerId:t,storeHash:n,channelId:i}})},new((d=void 0)||(d=Promise))(function(e,t){function n(e){try{r(c.next(e))}catch(e){t(e)}}function i(e){try{r(c.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof d?r:new d(function(e){e(r)})).then(n,i)}r((c=c.apply(a,s||[])).next())});var a,s,d,c}}class rt 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}}!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.MissingPaymentProviderCustomer=13]="MissingPaymentProviderCustomer",e[e.MissingPaymentRedirectUrl=14]="MissingPaymentRedirectUrl",e[e.MissingPaymentStatus=15]="MissingPaymentStatus",e[e.MissingPaymentToken=16]="MissingPaymentToken",e[e.MissingShippingAddress=17]="MissingShippingAddress"}(tt||(tt={}));class ot extends rt{constructor(e){super(function(e){switch(e){case tt.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case tt.MissingCart:return"Unable to proceed because cart data is unavailable.";case tt.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case tt.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case tt.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case tt.MissingCheckoutConfig:case tt.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case tt.MissingOrder:return"Unable to proceed because order data is unavailable.";case tt.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case tt.MissingPayment:return"Unable to proceed because payment data is unavailable.";case tt.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case tt.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case tt.MissingPaymentProviderCustomer:return"Unable to proceed because payment provider customer is unavailable.";case tt.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"}}!function(e){e.UpdateBillingAddressRequested="UPDATE_BILLING_ADDRESS_REQUESTED",e.UpdateBillingAddressSucceeded="UPDATE_BILLING_ADDRESS_SUCCEEDED",e.UpdateBillingAddressFailed="UPDATE_BILLING_ADDRESS_FAILED",e.ContinueAsGuestRequested="CONTINUE_AS_GUEST_REQUESTED",e.ContinueAsGuestSucceeded="CONTINUE_AS_GUEST_SUCCEEDED",e.ContinueAsGuestFailed="CONTINUE_AS_GUEST_FAILED"}(nt||(nt={}));class at extends rt{constructor(e){super(e||"Unable to continue as a guest because the customer is already signed in."),this.name="UnableToContinueAsGuestError",this.type="unable_to_continue_as_guest"}}var st;class dt{constructor(e,t){this._requestSender=e,this._subscriptionActionCreator=t}continueAsGuest(e,t){return n=>{const i=n.getState(),r=i.checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);const o=i.customer.getCustomer();if(o&&!o.isGuest)throw new at;const a=i.billingAddress.getBillingAddress();let s;if(a){const{country:t}=a,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(a,["country"]);s=Object.assign(Object.assign({},n),e)}else s=e;const d=!$(a);return I(g(C(l(nt.ContinueAsGuestRequested)),f(()=>{return e=this,n=void 0,o=function*(){const{body:e}=yield this._createOrUpdateBillingAddress(r.id,s,d,t);return l(nt.ContinueAsGuestSucceeded,e)},new((i=void 0)||(i=Promise))(function(t,r){function a(e){try{d(o.next(e))}catch(e){r(e)}}function s(e){try{d(o.throw(e))}catch(e){r(e)}}function d(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((o=o.apply(e,n||[])).next())});var e,n,i,o})).pipe(P(e=>Ke(nt.ContinueAsGuestFailed,e))),this._updateCustomerConsent(e,t))}}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout();if(!o)throw new ot(tt.MissingCheckout);i.next(l(nt.UpdateBillingAddressRequested));const a=r.billingAddress.getBillingAddress(),s=!$(a),d=Object.assign(Object.assign({},e),{email:void 0===e.email&&a?a.email:e.email});a&&a.id&&(d.id=a.id),this._createOrUpdateBillingAddress(o.id,d,s,t).then(({body:e})=>{i.next(l(nt.UpdateBillingAddressSucceeded,e)),i.complete()}).catch(e=>{i.error(h(nt.UpdateBillingAddressFailed,e))})})}_updateCustomerConsent({email:e,acceptsAbandonedCartEmails:t,acceptsMarketingNewsletter:n},i){return null==t&&null==n?v():this._subscriptionActionCreator.updateSubscriptions({email:e,acceptsMarketingNewsletter:n||!1,acceptsAbandonedCartEmails:t||!1},i)}_createOrUpdateBillingAddress(e,t,n,i){return n?this._requestSender.updateAddress(e,t,i):this._requestSender.createAddress(e,t,i)}}class ct extends rt{constructor(e){super(e||"Your checkout could not be processed because your cart is empty. Please add items to your cart and try again."),this.name="EmptyCartError",this.type="empty_cart"}}!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(st||(st={}));const lt=st;const ut={include:["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"].join(",")};class ht{constructor(e){this._requestSender=e}createAddress(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/billing-address`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(i,{body:t,params:ut,headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}updateAddress(e,t,{timeout:n}={}){const{id:i}=t,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["id"]),o=`/api/storefront/checkouts/${e}/billing-address/${i}`,a=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.put(o,{params:ut,body:r,headers:a,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}var pt,mt;function yt(e,t){const n=u((e,t)=>t.type===pt.Synchronize?t.payload:e,e.getState(),{stateTransformer:t});return e.subscribe(e=>{n.dispatch(l(pt.Synchronize,e))},{initial:!1}),n}!function(e){e.Synchronize="SYNCHRONIZE"}(pt||(pt={})),function(e){e.ClearError="CLEAR_ERROR"}(mt||(mt={}));class gt{clearError(e){return{type:mt.ClearError,payload:e}}}class ft{constructor(e,t){this._requestSender=e,this._config=t}sendRequest(e,t){return this._requestSender.sendRequest(e,t)}get(e,t){return this._requestSender.get(e,t)}post(e,t){return this._requestSender.post(this._prefixed(e),t)}put(e,t){return this._requestSender.put(this._prefixed(e),t)}patch(e,t){return this._requestSender.patch(this._prefixed(e),t)}delete(e,t){return this._requestSender.delete(this._prefixed(e),t)}_prefixed(e){const t=this._config.getBasePath();return!this._config.getFeatures()["CHECKOUT-9950.update_sf_checkout_url_for_subfolder"]||!t||t.endsWith("/checkout")||/^https?:\/\//.test(e)?e:`${t}${e}`}}function vt(){try{return"production"}catch(e){return"development"}}class _t{constructor(e){this._console=e}log(...e){this._logToConsole("log",...e)}info(...e){this._logToConsole("info",...e)}warn(...e){this._logToConsole("warn",...e)}error(...e){this._logToConsole("error",...e)}debug(...e){this._logToConsole("debug",...e)}_logToConsole(e,...t){this._console&&this._console[e]&&this._console[e].call(this._console,...t)}}class St{log(){}info(){}warn(){}error(){}debug(){}}const It=function(e=!0){return e?new _t(console):new St}("test"!==vt());function wt(){return It}function Ct(e,t,n){const i=new WeakMap;function r(e){return(...n)=>{const r=n[n.length-1],{useCache:o}=(a=r)&&"boolean"==typeof a.useCache?r:{useCache:!1};var a;if(!o)return e.call(this,...n);const s=i.get(this)||{};var d;return i.get(this)||i.set(this,s),s[t]||(s[t]=(d=e,Pe(function(...e){const t=d.call(this,...e);return t instanceof m?_(t).pipe(D()):"function"==typeof t?Pe(e=>_(t(e)).pipe(D()),{isEqual:Y}):t},{isEqual:Y}))),s[t].call(this,...n)}}return{get(){if("function"!=typeof n.value)throw new Error("Decorator should be used in functions");const e=r.call(this,n.value);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e}}}var bt;!function(e){e.LoadConfigRequested="LOAD_CONFIG_REQUESTED",e.LoadConfigSucceeded="LOAD_CONFIG_SUCCEEDED",e.LoadConfigFailed="LOAD_CONFIG_FAILED"}(bt||(bt={}));class Pt{constructor(e){this._configRequestSender=e}loadConfig(e){return m.create(t=>{t.next(l(bt.LoadConfigRequested)),this._configRequestSender.loadConfig(e).then(e=>{t.next(l(bt.LoadConfigSucceeded,e.body)),t.complete()}).catch(e=>{t.error(h(bt.LoadConfigFailed,e))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Ct],Pt.prototype,"loadConfig",null);const Ot={body:{},headers:{},status:0};class Et extends rt{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||Ot;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}class At extends Et{constructor(e){super(e,{message:e.body.title}),this.name="CheckoutNotAvailableError",this.type="checkout_not_available"}}const Tt="This API endpoint is for internal use only and may change in the future";class kt{constructor(e){this._requestSender=e}loadConfig({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-settings",{timeout:e,headers:Object.assign({Accept:lt.JsonV1,"X-API-INTERNAL":Tt},et),params:t}).catch(e=>{if(e.status>=400&&e.status<500)throw new At(e);throw e})}}var Dt;!function(e){e.ApplyCouponRequested="APPLY_COUPON_REQUESTED",e.ApplyCouponSucceeded="APPLY_COUPON_SUCCEEDED",e.ApplyCouponFailed="APPLY_COUPON_FAILED",e.RemoveCouponRequested="REMOVE_COUPON_REQUESTED",e.RemoveCouponSucceeded="REMOVE_COUPON_SUCCEEDED",e.RemoveCouponFailed="REMOVE_COUPON_FAILED"}(Dt||(Dt={}));class Mt{constructor(e){this._couponRequestSender=e}applyCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);i.next(l(Dt.ApplyCouponRequested)),this._couponRequestSender.applyCoupon(r.id,e,t).then(({body:e})=>{i.next(l(Dt.ApplyCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Dt.ApplyCouponFailed,e))})})}removeCoupon(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);i.next(l(Dt.RemoveCouponRequested)),this._couponRequestSender.removeCoupon(r.id,e,t).then(({body:e})=>{i.next(l(Dt.RemoveCouponSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Dt.RemoveCouponFailed,e))})})}}const zt=["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","customer.customerGroup","payments","promotions.banners"];var xt,Nt,Rt,Ft;function Lt(e){return Ie(e).join(",")}!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(xt||(xt={}));class jt{constructor(e){this._requestSender=e}applyCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Lt([...zt,xt.AvailableShippingOptions])},body:{couponCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}removeCoupon(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/coupons/${t}`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Lt([...zt,xt.AvailableShippingOptions])}}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}!function(e){e.ApplyGiftCertificateRequested="APPLY_GIFT_CERTIFICATE_REQUESTED",e.ApplyGiftCertificateSucceeded="APPLY_GIFT_CERTIFICATE_SUCCEEDED",e.ApplyGiftCertificateFailed="APPLY_GIFT_CERTIFICATE_FAILED",e.RemoveGiftCertificateRequested="REMOVE_GIFT_CERTIFICATE_REQUESTED",e.RemoveGiftCertificateSucceeded="REMOVE_GIFT_CERTIFICATE_SUCCEEDED",e.RemoveGiftCertificateFailed="REMOVE_GIFT_CERTIFICATE_FAILED"}(Nt||(Nt={}));class Bt{constructor(e){this._giftCertificateRequestSender=e}applyGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);i.next(l(Nt.ApplyGiftCertificateRequested)),this._giftCertificateRequestSender.applyGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.ApplyGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.ApplyGiftCertificateFailed,e))})})}removeGiftCertificate(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);i.next(l(Nt.RemoveGiftCertificateRequested)),this._giftCertificateRequestSender.removeGiftCertificate(r.id,e,t).then(({body:e})=>{i.next(l(Nt.RemoveGiftCertificateSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Nt.RemoveGiftCertificateFailed,e))})})}}class Ut{constructor(e){this._requestSender=e}applyGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(i,{headers:r,timeout:n,params:{include:Lt(zt)},body:{giftCertificateCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}removeGiftCertificate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/gift-certificates/${t}`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.delete(i,{headers:r,timeout:n,params:{include:Lt(zt)}}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}function qt(e){return e&&"resolveIds"in e}class Vt extends rt{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Gt{constructor(e){var t,n,i;this._factories={},this._instances={},this._defaultToken=null!==(t=null==e?void 0:e.defaultToken)&&void 0!==t?t:"default",this._useFallback=null===(n=null==e?void 0:e.useFallback)||void 0===n||n,this._tokenResolver=null!==(i=null==e?void 0:e.tokenResolver)&&void 0!==i?i:e=>e}get(e,t){try{return this._getInstance(e||this._defaultToken,t||e||this._defaultToken)}catch(e){if(!this._useFallback)throw e;return this._getInstance(this._defaultToken,t||this._defaultToken)}}getFactory(e,t){const n=this._tokenResolver(e,Object.keys(this._factories),t);return n?this._factories[n]:void 0}register(e,t){if(this._hasFactory(e))throw new Vt(`'${e}' is already registered.`);this._factories[e]=t}_hasFactory(e){return!!this._factories[e]}_hasInstance(e){return!!this._instances[e]}_getInstance(e,t){if(!this._hasInstance(t)){const n=this.getFactory(e);if(!n)throw new Vt(`'${e}' is not registered.`);this._instances[t]=n()}return this._instances[t]}}class Ht{constructor(e=!1){this._useFallback=e,this._registry=new Gt({tokenResolver:this._resolveToken.bind(this),defaultToken:this._encodeToken({default:!0}),useFallback:this._useFallback})}get(e){return this._registry.get(this._encodeToken(e))}getFactory(e,t){try{return this._registry.getFactory(this._encodeToken(e),t)}catch(e){return}}getUseFallback(){return this._useFallback}register(e,t){this._registry.register(this._encodeToken(e),t)}_encodeToken(e){return btoa(JSON.stringify(e))}_decodeToken(e){return JSON.parse(atob(e))}_resolveToken(e,t,n){var i;const r=this._decodeToken(e),o=[];t.forEach(e=>{const t=this._decodeToken(e),n={token:e,matches:0,default:!1,totalKeys:Object.keys(t).length};for(const[e,i]of Object.entries(t)){if(e in r&&r[e]!==i){n.matches=0;break}e in r&&r[e]===i&&n.matches++,"default"===e&&!0===i&&(n.default=!0)}o.push(n)});const a=o.sort((e,t)=>t.matches-e.matches).filter(e=>e.matches>0);a.length>1&&a[0].matches===a[1].matches&&"development"===vt()&&wt().warn("The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.");const s=Object.keys(r).length;if(n){const e=a.find(e=>e.matches===s&&e.matches===e.totalKeys);if(!e)throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)} with exact match.`);return e.token}const d=a[0];if(d&&d.token)return d.token;if(this._useFallback){const e=null===(i=o.find(e=>e.default))||void 0===i?void 0:i.token;if(e)return e}throw new Error(`Unable to resolve to a registered token with the provided token for ${JSON.stringify(r)}.`)}}function Wt(e){const t=e;return"object"==typeof t&&"object"==typeof t.payload&&"string"==typeof t.payload.token}!function(e){e.BuyNow="BUY_NOW"}(Rt||(Rt={})),function(e){e.SignInCustomerRequested="SIGN_IN_CUSTOMER_REQUESTED",e.SignInCustomerSucceeded="SIGN_IN_CUSTOMER_SUCCEEDED",e.SignInCustomerFailed="SIGN_IN_CUSTOMER_FAILED",e.SignOutCustomerRequested="SIGN_OUT_CUSTOMER_REQUESTED",e.SignOutCustomerSucceeded="SIGN_OUT_CUSTOMER_SUCCEEDED",e.SignOutCustomerFailed="SIGN_OUT_CUSTOMER_FAILED",e.CreateCustomerRequested="CREATE_CUSTOMER_REQUESTED",e.CreateCustomerSucceeded="CREATE_CUSTOMER_SUCCEEDED",e.CreateCustomerFailed="CREATE_CUSTOMER_FAILED",e.CreateCustomerAddressRequested="CREATE_CUSTOMER_ADDRESS_REQUESTED",e.CreateCustomerAddressSucceeded="CREATE_CUSTOMER_ADDRESS_SUCCEEDED",e.CreateCustomerAddressFailed="CREATE_CUSTOMER_ADDRESS_FAILED",e.StripeLinkAuthenticated="STRIPE_LINK_AUTHENTICATED"}(Ft||(Ft={}));var $t,Yt,Kt;class Jt{constructor(e,t,n){this._customerRequestSender=e,this._checkoutActionCreator=t,this._spamProtectionActionCreator=n}createCustomer(e,t){return n=>{const i=n.getState().config.getStoreConfigOrThrow(),{isStorefrontSpamProtectionEnabled:r}=i.checkoutSettings,o=i=>_(this._customerRequestSender.createAccount(Object.assign(Object.assign({},e),{token:i}),t)).pipe(M(()=>g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Ft.CreateCustomerSucceeded)))));return g(C(l(Ft.CreateCustomerRequested)),r?_(this._spamProtectionActionCreator.execute()(n)).pipe(M(e=>{var t;return Wt(e)?g(C(e),o(null===(t=e.payload)||void 0===t?void 0:t.token)):C(e)})):o()).pipe(P(e=>Ke(Ft.CreateCustomerFailed,e)))}}createAddress(e,t){return g(C(l(Ft.CreateCustomerAddressRequested)),f(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._customerRequestSender.createAddress(e,t);return l(Ft.CreateCustomerAddressSucceeded,n)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Ke(Ft.CreateCustomerAddressFailed,e)))}signInCustomer(e,t){return n=>{const i=n.getState().checkout.getCheckoutOrThrow(),r=i.cart.source===Rt.BuyNow?i.id:void 0;return g(C(l(Ft.SignInCustomerRequested)),_(this._customerRequestSender.signInCustomer(Object.assign(Object.assign({},e),{cartId:r}),t)).pipe(M(({body:e})=>e.data.persistentCartRetrievalInformation?g(this._checkoutActionCreator.loadCheckout(e.data.persistentCartRetrievalInformation.id,t)(n),C(l(Ft.SignInCustomerSucceeded,e.data))):g(this._checkoutActionCreator.loadCurrentCheckout(t)(n),C(l(Ft.SignInCustomerSucceeded,e.data)))))).pipe(P(e=>Ke(Ft.SignInCustomerFailed,e)))}}signOutCustomer(e){return t=>{const n=t.getState().checkout.getCheckoutOrThrow(),i=n.cart.source===Rt.BuyNow?n.id:void 0;return g(C(l(Ft.SignOutCustomerRequested)),_(this._customerRequestSender.signOutCustomer(e,i)).pipe(M(({body:n})=>g(this._checkoutActionCreator.loadCurrentCheckout(e)(t),C(l(Ft.SignOutCustomerSucceeded,n.data)))))).pipe(P(e=>Ke(Ft.SignOutCustomerFailed,e)))}}}class Zt{constructor(e){this._requestSender=e}createAccount(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer",{timeout:t,headers:et,body:e})}createAddress(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer-address",{timeout:t,headers:et,body:e})}signInCustomer(e,{timeout:t}={}){return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:t,headers:et,body:e})}signOutCustomer({timeout:e}={},t){return this._requestSender.delete("/internalapi/v1/checkout/customer",Object.assign({timeout:e,headers:et},t&&{body:{cartId:t}}))}}function Qt(e,t,n){t.forEach(t=>{qt(t)&&t.resolveIds.forEach(i=>{e.getFactory(i,!0)||e.register(i,()=>t(n))})})}!function(e){e.SignInFailed="CUSTOMER_STRATEGY_SIGN_IN_FAILED",e.SignInRequested="CUSTOMER_STRATEGY_SIGN_IN_REQUESTED",e.SignInSucceeded="CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED",e.SignOutFailed="CUSTOMER_STRATEGY_SIGN_OUT_FAILED",e.SignOutRequested="CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED",e.SignOutSucceeded="CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED",e.ExecutePaymentMethodCheckoutFailed="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_FAILED",e.ExecutePaymentMethodCheckoutRequested="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_REQUESTED",e.ExecutePaymentMethodCheckoutSucceeded="CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_SUCCEEDED",e.InitializeFailed="CUSTOMER_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="CUSTOMER_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="CUSTOMER_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED"}($t||($t={}));class Xt{constructor(e,t,n){this._strategyRegistry=e,this._strategyRegistryV2=t,this._paymentIntegrationService=n}signIn(e,t){return m.create(n=>{const i=t&&t.methodId,r={methodId:i};n.next(l($t.SignInRequested,void 0,r)),this._getStrategy(i).signIn(e,t).then(()=>{n.next(l($t.SignInSucceeded,void 0,r)),n.complete()}).catch(e=>{n.error(h($t.SignInFailed,e,r))})})}signOut(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l($t.SignOutRequested,void 0,i)),this._getStrategy(n).signOut(e).then(()=>{t.next(l($t.SignOutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h($t.SignOutFailed,e,i))})})}executePaymentMethodCheckout(e){return m.create(t=>{const n=e&&e.methodId,i={methodId:n};t.next(l($t.ExecutePaymentMethodCheckoutRequested,void 0,i)),this._getStrategy(n).executePaymentMethodCheckout(e).then(()=>{t.next(l($t.ExecutePaymentMethodCheckoutSucceeded,void 0,i)),t.complete()}).catch(e=>{t.error(h($t.ExecutePaymentMethodCheckoutFailed,e,i))})})}initialize(e){return t=>m.create(n=>{var i;const r=t.getState(),o=e&&e.methodId,a={methodId:o};if(Qt(this._strategyRegistryV2,null!==(i=null==e?void 0:e.integrations)&&void 0!==i?i:[],this._paymentIntegrationService),o&&r.customerStrategies.isInitialized(o))return n.complete();n.next(l($t.InitializeRequested,void 0,a)),this._getStrategy(o).initialize(e).then(()=>{n.next(l($t.InitializeSucceeded,void 0,a)),n.complete()}).catch(e=>{n.error(h($t.InitializeFailed,e,a))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=e&&e.methodId,o={methodId:r};if(r&&!i.customerStrategies.isInitialized(r))return n.complete();n.next(l($t.DeinitializeRequested,void 0,o)),this._getStrategy(r).deinitialize(e).then(()=>{n.next(l($t.DeinitializeSucceeded,void 0,o)),n.complete()}).catch(e=>{n.error(h($t.DeinitializeFailed,e,o))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l($t.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l($t.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h($t.WidgetInteractionFailed,e,i))})})}_getStrategy(e){let t;try{t=this._strategyRegistryV2.get({id:e||""})}catch(n){t=this._strategyRegistry.get(e)}return t}}function en(e,t=[]){return Array.isArray(t)?Lt([...e,...t]):function(e,t){const n=ie(me(t,e=>!e)),i=ie(L(t));return Lt([...R(e,n),...i])}(e,t)}class tn{constructor(e){this._requestSender=e}loadCheckout(e,{params:{include:t}={},timeout:n}={}){const i=`/api/storefront/checkout/${e}`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.get(i,{params:{include:en(zt,t)},headers:r,timeout:n}).catch(e=>{if(e.status>=400&&e.status<500)throw new At(e);throw e})}updateCheckout(e,t,{params:{include:n}={},timeout:i}={}){const r=`/api/storefront/checkout/${e}`,o=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.put(r,{params:{include:en(zt,n)},body:t,headers:o,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}!function(e){e.LoadCheckoutRequested="LOAD_CHECKOUT_REQUESTED",e.LoadCheckoutSucceeded="LOAD_CHECKOUT_SUCCEEDED",e.LoadCheckoutFailed="LOAD_CHECKOUT_FAILED",e.UpdateCheckoutRequested="UPDATE_CHECKOUT_REQUESTED",e.UpdateCheckoutSucceeded="UPDATE_CHECKOUT_SUCCEEDED",e.UpdateCheckoutFailed="UPDATE_CHECKOUT_FAILED"}(Yt||(Yt={})),function(e){e.HydrateInitialState="HYDRATE_INITIAL_STATE"}(Kt||(Kt={}));var nn;class rn{constructor(e,t,n){this._checkoutRequestSender=e,this._configActionCreator=t,this._formFieldsActionCreator=n}loadCheckout(e,t){return()=>g(C(l(Yt.LoadCheckoutRequested)),I(this._configActionCreator.loadConfig({useCache:!0,timeout:null==t?void 0:t.timeout,params:{checkoutId:e}}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==t?void 0:t.timeout})),f(()=>this._checkoutRequestSender.loadCheckout(e,t).then(({body:e})=>l(Yt.LoadCheckoutSucceeded,this._transformCustomerAddresses(e))))).pipe(P(e=>Ke(Yt.LoadCheckoutFailed,e)))}loadDefaultCheckout(e){return t=>g(C(l(Yt.LoadCheckoutRequested)),I(this._configActionCreator.loadConfig({useCache:!0,timeout:null==e?void 0:e.timeout}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==e?void 0:e.timeout})),f(()=>{return n=this,i=void 0,o=function*(){const n=t.getState().config.getContextConfig();if(!n||!n.checkoutId)throw new ot(tt.MissingCheckoutConfig);const{body:i}=yield this._checkoutRequestSender.loadCheckout(n.checkoutId,e);return l(Yt.LoadCheckoutSucceeded,this._transformCustomerAddresses(i))},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Ke(Yt.LoadCheckoutFailed,e)))}updateCheckout(e,t){return n=>new m(i=>{const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);i.next(l(Yt.UpdateCheckoutRequested)),this._checkoutRequestSender.updateCheckout(r.id,e,t).then(({body:e})=>{i.next(l(Yt.UpdateCheckoutSucceeded,e)),i.complete()}).catch(e=>{i.error(h(Yt.UpdateCheckoutFailed,e))})})}loadCurrentCheckout(e){return t=>{const n=t.getState().checkout.getCheckout();if(!n)throw new ot(tt.MissingCheckout);return this.loadCheckout(n.id,e)(t)}}hydrateInitialState(e){return{type:Kt.HydrateInitialState,payload:e}}_transformCustomerAddresses(e){return Object.assign(Object.assign({},e),{customer:Object.assign(Object.assign({},e.customer),{addresses:e.customer.addresses.map(e=>Object.assign(Object.assign({},e),{shouldSaveAddress:!1}))})})}}!function(e){e.LoadFormFieldsRequested="LOAD_FORM_FIELDS_REQUESTED",e.LoadFormFieldsSucceeded="LOAD_FORM_FIELDS_SUCCEEDED",e.LoadFormFieldsFailed="LOAD_FORM_FIELDS_FAILED"}(nn||(nn={}));var on;class an{constructor(e){this._formFieldsRequestSender=e}loadFormFields(e){return g(C(l(nn.LoadFormFieldsRequested)),f(()=>{return t=this,n=void 0,r=function*(){const{body:t}=yield this._formFieldsRequestSender.loadFields(e);return l(nn.LoadFormFieldsSucceeded,t)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r})).pipe(P(e=>Ke(nn.LoadFormFieldsFailed,e)))}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Ct],an.prototype,"loadFormFields",null);class sn{constructor(e){this._requestSender=e}loadFields({timeout:e}={}){return this._requestSender.get("/api/storefront/form-fields",{timeout:e,headers:Object.assign({Accept:lt.JsonV1,"X-API-INTERNAL":Tt},et)})}}class dn extends rt{constructor(){super("You haven't complete our spam protection challenge. Please try again."),this.name="SpamProtectionChallengeNotCompletedError",this.type="spam_protection_challenge_not_completed"}}class cn extends rt{constructor(){super("We were not able to complete your spam protection verification. Please try again."),this.name="SpamProtectionFailedError",this.type="spam_protection_failed"}}!function(e){e.InitializeFailed="SPAM_PROTECTION_INITIALIZE_FAILED",e.InitializeSucceeded="SPAM_PROTECTION_INITIALIZE_SUCCEEDED",e.InitializeRequested="SPAM_PROTECTION_INITIALIZE_REQUESTED",e.VerifyCheckoutRequested="SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED",e.VerifyCheckoutSucceeded="SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED",e.VerifyCheckoutFailed="SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED",e.ExecuteRequested="SPAM_PROTECTION_EXECUTE_REQUESTED",e.ExecuteSucceeded="SPAM_PROTECTION_EXECUTE_SUCCEEDED",e.ExecuteFailed="SPAM_PROTECTION_EXECUTE_FAILED"}(on||(on={}));var ln,un,hn,pn=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class mn{constructor(e,t){this._googleRecaptcha=e,this._requestSender=t}initialize(e){return t=>g(C(l(on.InitializeRequested,void 0)),f(()=>pn(this,void 0,void 0,function*(){const n=e?e.containerId:"spamProtectionContainer";if(document.getElementById(n)&&this._googleRecaptcha.reset(n),!e&&!document.getElementById(n)){const e=document.createElement("div");e.setAttribute("id",n),document.body.appendChild(e)}const i=t.getState().config.getStoreConfigOrThrow().checkoutSettings.googleRecaptchaSitekey;return yield this._googleRecaptcha.load(n,i),l(on.InitializeSucceeded)}))).pipe(P(e=>Ke(on.InitializeFailed,e)))}verifyCheckoutSpamProtection(){return e=>f(()=>{const t=e.getState().checkout.getCheckout();if(!t)throw new ot(tt.MissingCheckout);return g(C(l(on.VerifyCheckoutRequested)),_(this.execute()(e)).pipe(M(e=>Wt(e)&&e.payload?_(this._requestSender.validate(t.id,e.payload.token)).pipe(M(({body:t})=>g(C(e),C(l(on.VerifyCheckoutSucceeded,t))))):C(e)))).pipe(P(e=>Ke(on.VerifyCheckoutFailed,e)))})}execute(){return e=>g(C(l(on.ExecuteRequested)),this.initialize()(e),this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>pn(this,void 0,void 0,function*(){if(e instanceof dn)throw e;if(e||!t)throw new cn;return l(on.ExecuteSucceeded,{token:t})})))).pipe(P(e=>Ke(on.ExecuteFailed,e)))}}class yn{constructor(e=window){this._window=e}create(e){return new this._window.MutationObserver(e)}}!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"}(ln||(ln={}));class gn extends rt{constructor(e){super(function(e){switch(e){case ln.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ln.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ln.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ln.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"}}class fn extends rt{constructor(){super("Spam protection is not loaded. Please try again."),this.name="SpamProtectionNotLoadedError",this.type="spam_protection_failed"}}class vn{constructor(e,t){this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=Pe((e,t,n)=>{const i=new y;if(!n)throw new Error;return this._widgetId=e.render(n.id,{sitekey:t,size:"invisible",callback:()=>{i.next({token:e.getResponse(this._widgetId)}),e.reset(this._widgetId)},"error-callback":()=>{i.next({error:new cn})}}),i},{isEqual:(e,t)=>e===t})}load(e,t){return this.googleRecaptchaScriptLoader.load().then(n=>{n&&(this._event$=this._memoized(n,t,document.getElementById(e)),this._recaptcha=n)}).catch(e=>{throw e})}reset(e){var t;const n=document.getElementById(e);null==n||n.remove(),null===(t=this._recaptcha)||void 0===t||t.reset(this._widgetId)}execute(){return f(()=>{const e=this._event$,t=this._recaptcha;if(!e||!t)throw new gn(ln.SpamProtectionNotInitialized);return f(()=>{const e=document.querySelector('iframe[src*="bframe"]');return e?C(e):b(new fn)}).pipe(k(e=>e.pipe(O(250),M((e,t)=>t<28?C(e):b(e)))),M(n=>(this._watchRecaptchaChallengeWindow(e,n),t.execute(this._widgetId),e)),P(e=>C({error:e})))})}_watchRecaptchaChallengeWindow(e,t){const n=t.parentElement;if(!n)throw new fn;const i=n.parentElement;if(!i)throw new fn;this.mutationObserverFactory.create(()=>{"hidden"===i.style.visibility&&e.next({error:new dn})}).observe(i,{attributes:!0,attributeFilter:["style"]})}}class _n{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise}_loadScript(){const e="initRecaptcha",t=[`onload=${e}`,"render=explicit"].join("&");return new Promise((n,i)=>{this._window[e]=()=>n(this._window.grecaptcha),this._scriptLoader.loadScript(`//www.google.com/recaptcha/api.js?${t}`).catch(e=>{this._loadPromise=void 0,i(e)})})}}function Sn(e){return new vn(new _n(e),new yn)}class In{constructor(e){this._requestSender=e}validate(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/spam-protection`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(i,{body:{token:t},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}class wn{constructor(e,t){this._store=e,this._customerActionCreator=t}signIn(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))}signOut(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}function Cn(e){if(!/^(https?:)?\/\//.test(e))throw new Vt("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const n=t.port&&-1!==e.indexOf(`${t.hostname}:${t.port}`)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:`${t.protocol}//${t.hostname}${n?`:${n}`:""}`,pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}class bn extends rt{constructor(e){super(e||"Unable to proceed due to no extension configured for this region."),this.name="ExtensionNotFoundError",this.type="extension_not_found"}}function Pn(e,t){return e.type===t}!function(e){e.LoadExtensionsRequested="LOAD_EXTENSIONS_REQUESTED",e.LoadExtensionsSucceeded="LOAD_EXTENSIONS_SUCCEEDED",e.LoadExtensionsFailed="LOAD_EXTENSIONS_FAILED",e.RenderExtensionRequested="RENDER_EXTENSION_REQUESTED",e.RenderExtensionSucceeded="RENDER_EXTENSION_SUCCEEDED",e.RenderExtensionFailed="RENDER_EXTENSION_FAILED"}(un||(un={}));class On{constructor(e,t,n){this._targetWindow=t,this._context=n,this._targetOrigin="*"===e?"*":Cn(e).origin}post(e,t){const n=this._targetWindow;if(window===n)return;if(!n)throw new Error("Unable to post message because target window is not set.");const i=t&&S(window,"message").pipe(A(e=>e.origin===this._targetOrigin&&Pn(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),T(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),z(1)).toPromise();return n.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),i}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}function En(e){var t;const n=null===(t=document.querySelector(`[data-extension-id="${e.id}"]`))||void 0===t?void 0:t.querySelector("iframe");if(!(null==n?void 0:n.contentWindow))throw new bn(`Unable to post due to no extension rendered for ID: ${e.id}.`);return new On(e.url,n.contentWindow)}!function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(hn||(hn={}));class An{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}class Tn extends rt{constructor(e){super(e||"Unable to proceed because the required element is unexpectedly detached from the page."),this.name="UnexpectedDetachmentError",this.type="unexpected_detachment"}}var kn;class Dn{constructor(e){this._mutationObserver=e}ensurePresence(e,t){return n=this,i=void 0,o=function*(){const n=new An(t),i=this._mutationObserver.create(t=>{t.forEach(t=>{0!==Array.from(t.removedNodes).filter(t=>e.some(e=>t===e||t.contains(e))).length&&n.cancel(new Tn)})});i.observe(document.body,{childList:!0,subtree:!0});try{const e=yield n.promise;return i.disconnect(),e}catch(e){throw i.disconnect(),e}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function Mn(e,t){const{iframeResizer:n}=Ve(785);return n(e,t)}class zn extends rt{constructor(e){super(e||"Unable to load an extension"),this.name="ExtensionNotLoadedError",this.type="extension_not_loaded"}}!function(e){e.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",e.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",e.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(kn||(kn={}));class xn{constructor(e){this._options=e}createFrame(e,t,n,i){const r=document.getElementById(t),{timeout:o=6e4}=this._options||{};if(!r)throw new zn("Unable to embed the iframe because the container element could not be found.");const a=document.createElement("iframe");return a.src=e,a.style.border="none",a.style.display="none",a.style.width="100%",r.appendChild(a),this._toResizableFrame(a,o,n,i).catch(e=>{throw r.removeChild(a),e})}_toResizableFrame(e,t,n,i){return r=this,o=void 0,s=function*(){const r=new Dn(new yn),o=new Promise((r,o)=>{const a=window.setTimeout(()=>{try{i()}catch(e){e instanceof Error&&console.error(`Extension rendering timed out after ${t}ms, and the callback function could not be executed. Error: ${e.message}`)}o(new zn("Unable to load the extension because the content could not be loaded."))},t),s=t=>{if(t.origin===Cn(e.src).origin&&Pn(t.data,kn.ResizeIframe)){e.style.display="";const t=Mn({autoResize:!1,scrolling:!1,sizeWidth:!1,heightCalculationMethod:"bodyOffset",initCallback:n},e);d(),r(t[t.length-1])}},d=()=>{window.removeEventListener("message",s),window.clearTimeout(a)};window.addEventListener("message",s)});return r.ensurePresence([e],o)},new((a=void 0)||(a=Promise))(function(e,t){function n(e){try{d(s.next(e))}catch(e){t(e)}}function i(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(n,i)}d((s=s.apply(r,o||[])).next())});var r,o,a,s}}class Nn{constructor(e,t,n){this._containerId=e,this._extension=t,this._config=n;const{cartId:i,parentOrigin:r}=this._config;this._url=new URL(this._extension.url),this._url.searchParams.set("extensionId",this._extension.id),this._url.searchParams.set("cartId",i),this._url.searchParams.set("parentOrigin",r)}attach(){var e,t,n,i,r;return t=this,n=void 0,r=function*(){if(null===(e=document.querySelector(`[data-extension-id="${this._extension.id}"]`))||void 0===e?void 0:e.querySelector("iframe"))return;const t=new xn,n=e=>{En(this._extension).post({type:e})};this._iframe=yield t.createFrame(this._url.toString(),this._containerId,()=>{n(hn.ExtensionReady)},()=>{n(hn.ExtensionFailed)});const i=document.getElementById(this._containerId);null==i||i.setAttribute("data-extension-id",this._extension.id)},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())})}detach(){this._iframe&&this._iframe.parentElement&&this._iframe.parentElement.removeChild(this._iframe)}}class Rn{constructor(e){this._requestSender=e}loadExtensions(e){return()=>m.create(t=>{t.next(l(un.LoadExtensionsRequested)),this._requestSender.loadExtensions(e).then(e=>{const n=e.body;t.next(l(un.LoadExtensionsSucceeded,n)),t.complete()}).catch(e=>{t.error(h(un.LoadExtensionsFailed,e))})})}renderExtension(e,t,n){return i=>m.create(r=>{return o=this,a=void 0,d=function*(){const o=i.getState(),{id:a}=o.cart.getCartOrThrow(),{links:{checkoutLink:s}}=o.config.getStoreConfigOrThrow(),d=o.extensions.getExtensionByRegion(t);try{if(!d)throw new bn(`Unable to proceed due to no extension configured for the region: ${t}.`);if(r.next(l(un.RenderExtensionRequested)),"worker"===d.type){const e=function(e){if(!window.Worker)throw new Error("Unable to load the extension's web worker: your browser does not support Web Workers.");try{const t=URL.createObjectURL(new Blob([`importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,"${e}"))))(importScripts);importScripts("${e}")`],{type:"text/javascript"}));return new Worker(t)}catch(e){throw new Error("Unable to load the extension's web worker")}}(d.url);n.add(d.id,e)}else{const t=new Nn(e,d,{cartId:a,parentOrigin:Cn(s).origin});yield t.attach()}r.next(l(un.RenderExtensionSucceeded)),r.complete()}catch(e){r.error(h(un.RenderExtensionFailed,e))}},new((s=void 0)||(s=Promise))(function(e,t){function n(e){try{r(d.next(e))}catch(e){t(e)}}function i(e){try{r(d.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s(function(e){e(r)})).then(n,i)}r((d=d.apply(o,a||[])).next())});var o,a,s,d})}}class Fn{constructor(e){this._requestSender=e}loadExtensions({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-extensions",{timeout:e,headers:Object.assign({Accept:lt.JsonV1},et),params:t})}}const Ln=function(e,t,n){return t&&n?jn(0,t,n):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,jn(e.prototype,n,i))}),t}(e)};function jn(e,t,n){if("function"!=typeof n.value)return n;let i=n.value;return{get(){const e=i.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=e}}}var Bn,Un;class qn{constructor(e){this._worker=e,this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,this._worker.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,this._worker.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["context"]);this.trigger(i,n)}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Ln],qn.prototype,"_handleMessage",null);class Vn{constructor(e,t){this._worker=e,this._context=t}post(e){if(!this._worker)throw new Error("WorkerPoster: Worker is not initialized or creation failed. Cannot post message.");this._worker.postMessage(Object.assign(Object.assign({},e),{context:this._context}))}}class Gn extends rt{constructor(e){super(e||"Unable to proceed due to unsupported extension command."),this.name="UnsupportedExtensionCommandError",this.type="unsupported_extension_command_error"}}class Hn extends rt{constructor(e){super(e||"Unable to proceed due to unsupported extension query."),this.name="UnsupportedExtensionQueryError",this.type="unsupported_extension_query_error"}}!function(e){e.ReloadCheckout="EXTENSION:RELOAD_CHECKOUT",e.ShowLoadingIndicator="EXTENSION:SHOW_LOADING_INDICATOR",e.SetIframeStyle="EXTENSION:SET_IFRAME_STYLE",e.ReRenderShippingForm="EXTENSION:RE_RENDER_SHIPPING_FORM",e.ReRenderShippingStep="EXTENSION:RE_RENDER_SHIPPING_STEP"}(Bn||(Bn={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(Un||(Un={}));class Wn{constructor(e={},t={},n={}){this._workers=e,this._commandListeners=t,this._queryListeners=n}add(e,t){this._workers[e]=t}listenForCommand(e,t,n){const i=this._getWorkerById(e);this._commandListeners[e]||(this._commandListeners[e]=new qn(i));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getWorkerById(e);this._queryListeners[e]||(this._queryListeners[e]=new qn(i));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()}post(e,t){if(!this._workers[e])throw new Error(`Worker with extensionId ${e} not found`);new Vn(this._workers[e],e).post(t)}clearCacheById(e){delete this._workers[e]}_getWorkerById(e){const t=this._workers[e];if(!t)throw new bn(`Worker with extensionId ${e} not found`);return t}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Gn}_validateQuery(e){if(Object.values(Un).includes(e))return e;throw new Hn}}function $n(e){return Cn(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,`www.${e.hostname}`))}var Yn;class Kn{constructor(e){this._sourceOrigins=[Cn(e).origin,$n(Cn(e)).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)}removeListener(e,t){const n=this._listeners[e];if(!n)return;const i=n.indexOf(t);i>=0&&n.splice(i,1)}trigger(e,t){const n=this._listeners[e.type];n&&n.forEach(n=>t?n(e,t):n(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!Pn(e.data,e.data.type))return;const t=e.data,{context:n}=t,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["context"]);this.trigger(i,n)}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Ln],Kn.prototype,"_handleMessage",null);class Jn{constructor(e,t,n={},i={},r={}){this._store=e,this._workerExtensionMessenger=t,this._commandListeners=n,this._queryListeners=i,this._posters=r}clearCacheByRegion(e){const t=this._getExtensionByRegion(e);"worker"!==t.type?this.clearCacheById(t.id):this._workerExtensionMessenger.clearCacheById(t.id)}clearCacheById(e){const t=this._getExtensionById(e);"worker"!==t.type?(this._commandListeners[e]&&delete this._commandListeners[e],this._queryListeners[e]&&delete this._queryListeners[e],this._posters[e]&&delete this._posters[e]):this._workerExtensionMessenger.clearCacheById(t.id)}listenForCommand(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForCommand(e,t,n);this._commandListeners[e]||(this._commandListeners[e]=new Kn(i.url));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,n){const i=this._getExtensionById(e);if("worker"===i.type)return this._workerExtensionMessenger.listenForQuery(e,t,n);this._queryListeners[e]||(this._queryListeners[e]=new Kn(i.url));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,i)=>{(null==i?void 0:i.extensionId)===e&&n(t,i)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}stopListen(e){"worker"!==this._getExtensionById(e).type?(this._commandListeners[e]&&this._commandListeners[e].stopListen(),this._queryListeners[e]&&this._queryListeners[e].stopListen()):this._workerExtensionMessenger.stopListen(e)}post(e,t){try{const n=this._getExtensionById(e);if("worker"===n.type)return void this._workerExtensionMessenger.post(e,t);this._posters[e]||(this._posters[e]=En(n)),this._posters[e].post(t)}catch(n){this.clearCacheById(e),console.log(`Unable to post event to extension(${e}) because extension iframe is not mounted.\nThe event that could not be delivered:`,t)}}_getExtensionById(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.id===e);if(!n)throw new bn(`Unable to proceed due to no extension found for ID: ${e}.`);return n}_getExtensionByRegion(e){var t;this._getExtensions();const n=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.region===e);if(!n)throw new bn(`Unable to proceed due to no extension found for region: ${e}.`);return n}_getExtensions(){if(this._extensions)return;const{extensions:{getExtensions:e}}=this._store.getState();if(this._extensions=e(),!this._extensions)throw new bn("Extension configurations not found.")}_validateCommand(e){if(Object.values(Bn).includes(e))return e;throw new Gn}_validateQuery(e){if(Object.values(Un).includes(e))return e;throw new Hn}}class Zn{constructor(e,t,n){this._store=e,this._extensionMessenger=t,this._subscribers=n,this._subscribed={},this._unsubscribers={},this._listeners={}}listen(){var e;const{data:{getExtensions:t}}=this._store.getState();null===(e=t())||void 0===e||e.forEach(e=>{if(this._listeners[e.id])return;const t=new Kn(e.url);t.addListener(kn.Subscribe,this._handleSubscribe.bind(this)),t.addListener(kn.Unsubscribe,this._handleUnsubscribe.bind(this)),t.listen(),this._listeners[e.id]=t})}broadcast(e){var t;const{data:{getExtensions:n}}=this._store.getState();null===(t=n())||void 0===t||t.forEach(t=>{this._subscribed[t.id]&&this._extensionMessenger.post(t.id,e)})}_handleSubscribe({payload:{eventType:e,extensionId:t}}){this._subscribed[t]=!0,this._unsubscribers[e]||(this._unsubscribers[e]=this._subscribers[e](this._store,this))}_handleUnsubscribe({payload:{eventType:e,extensionId:t}}){var n,i;delete this._subscribed[t],Object.keys(this._subscribed).length||(null===(i=(n=this._unsubscribers)[e])||void 0===i||i.call(n),delete this._unsubscribers[e])}}!function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}(Yn||(Yn={}));const Qn=(e,t)=>{var n;const{data:{getConsignments:i}}=e.getState();let r=null!==(n=i())&&void 0!==n?n:[];return e.subscribe(({data:{getConsignments:e}})=>{var n;const i=null!==(n=e())&&void 0!==n?n:[];i!==r&&(t.broadcast({type:Yn.ConsignmentsChanged,payload:{consignments:i,previousConsignments:r}}),r=i)},({data:{getConsignments:e}})=>e())};class Xn 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}}var ei,ti;!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"}(ei||(ei={}));class ni extends Xn{constructor(e){super(function(e){switch(e){case ei.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case ei.MissingCart:return"Unable to proceed because cart data is unavailable.";case ei.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case ei.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case ei.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case ei.MissingCheckoutConfig:case ei.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case ei.MissingOrder:return"Unable to proceed because order data is unavailable.";case ei.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case ei.MissingPayment:return"Unable to proceed because payment data is unavailable.";case ei.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case ei.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case ei.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"}}function ii(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}!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"}(ti||(ti={}));class ri extends Xn{constructor(e){super(function(e){switch(e){case ti.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ti.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ti.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ti.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"}}const oi={de:"eu",jp:"fe",uk:"eu",us:"na"};var ai,si,di,ci,li,ui;!function(e){e.en_US="en_US",e.en_GB="en_GB",e.de_DE="de_DE",e.fr_FR="fr_FR",e.it_IT="it_IT",e.es_ES="es_ES",e.ja_JP="ja_JP"}(ai||(ai={})),function(e){e.Home="Home",e.Product="Product",e.Cart="Cart",e.Checkout="Checkout",e.Other="Other"}(si||(si={})),function(e){e.USD="USD",e.EUR="EUR",e.GBP="GBP",e.JPY="JPY"}(di||(di={})),function(e){e.PayAndShip="PayAndShip",e.PayOnly="PayOnly"}(ci||(ci={})),function(e){e.Gold="Gold",e.LightGray="LightGray",e.DarkGray="DarkGray"}(li||(li={})),function(e){e.C0001="C0001"}(ui||(ui={}));var hi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pi{constructor(e){this.amazonPayV2ScriptLoader=e}initialize(e){return hi(this,void 0,void 0,function*(){this.amazonPayV2SDK=yield this.amazonPayV2ScriptLoader.load(e),this.buttonParentContainer=this.buttonParentContainer||this.createAmazonPayButtonParentContainer()})}deinitialize(){var e;return this.amazonPayV2Button=void 0,null===(e=this.buttonParentContainer)||void 0===e||e.remove(),this.buttonParentContainer=void 0,this.amazonPayV2SDK=void 0,Promise.resolve()}bindButton(e,t,n){this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${e}`,{amazonCheckoutSessionId:t,changeAction:n})}createButton(e,t){this.amazonPayV2Button=this.getAmazonPayV2SDK().Pay.renderButton(`#${e}`,t)}prepareCheckout(e){const t=this.prepareRequestConfig(e);this.getAmazonPayV2Button().onClick(()=>{this.getAmazonPayV2Button().initCheckout(t)})}prepareCheckoutWithCreationRequestConfig(e){this.getAmazonPayV2Button().onClick(()=>hi(this,void 0,void 0,function*(){const t=yield e();if(t){const e=this.prepareRequestConfig(t.createCheckoutSessionConfig,t.estimatedOrderAmount,t.productType);this.getAmazonPayV2Button().initCheckout(e)}}))}signout(){return hi(this,void 0,void 0,function*(){return this.amazonPayV2SDK&&this.amazonPayV2SDK.Pay.signout(),Promise.resolve()})}renderAmazonPayButton({buttonColor:e,checkoutState:t,containerId:n,decoupleCheckoutInitiation:i=!1,methodId:r,options:o,placement:a,isButtonMicroTextDisabled:s=!1}){const d=document.querySelector(`#${n}`);if(!d)return;const{id:c}=d.appendChild(this.getButtonParentContainer());o&&s&&(o.design=ui.C0001);const l=null!=o?o:this.getAmazonPayV2ButtonOptions(t,r,a,i,e);return this.createButton(c,l),this.getButtonParentContainer()}updateBuyNowFlowFlag(e){this.isBuyNowFlow=Boolean(e)}isPh4Enabled(e,t){const n=!!e["PROJECT-3483.amazon_pay_ph4"],i=!!e["INT-6885.amazon_pay_ph4_us_only"];return n&&i?"US"===t:n}prepareRequestConfig(e,t,n){const{publicKeyId:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["publicKeyId"]);return Object.assign(Object.assign({createCheckoutSessionConfig:this.isEnvironmentSpecific(i)?r:e},t&&{estimatedOrderAmount:t}),n&&{productType:n})}createAmazonPayButtonParentContainer(){const e=Math.random().toString(16).substr(-4),t=document.createElement("div");return t.id=`amazonpay_button_parent_container_${e}`,t}getAmazonPayV2ButtonOptions(e,t,n,i=!1,r=li.Gold){var o;const{getCart:a,getCheckout:s,getStoreConfigOrThrow:d,getPaymentMethodOrThrow:c}=this.getCheckoutState(e),{config:{merchantId:l,testMode:u},initializationData:h}=c(t);if(!h)throw new ni(ei.MissingPaymentMethod);const{checkoutLanguage:p,checkoutSessionMethod:m,createCheckoutSessionConfig:y,extractAmazonCheckoutSessionId:g,ledgerCurrency:f,publicKeyId:v="",isButtonMicroTextDisabled:_}=h;if(!l||!f)throw new ni(ei.MissingPaymentMethod);const S=Object.assign({merchantId:l,ledgerCurrency:f,checkoutLanguage:p,placement:n,buttonColor:r},_?{design:ui.C0001}:{});if(this.isBuyNowFlow)return Object.assign(Object.assign({},S),{sandbox:!!u});const I=a();S.productType=I&&0===function(e){return t=e.lineItems.physicalItems.filter(e=>!e.addedByPromotion),ye(t,(e,t)=>e+t.quantity,0);var t}(I)?ci.PayOnly:ci.PayAndShip;const{checkoutSettings:{features:w},storeProfile:{shopPath:C,storeCountryCode:b}}=d();if(this.isPh4Enabled(w,b)){if(!y)throw new ni(ei.MissingPaymentMethod);const e=null===(o=s())||void 0===o?void 0:o.outstandingBalance.toString(),t=null==I?void 0:I.currency.code,n=Object.assign({},S);let r;return this.isEnvironmentSpecific(v)?(n.publicKeyId=v,r=y):(n.sandbox=!!u,r=Object.assign(Object.assign({},y),{publicKeyId:v})),i||(n.createCheckoutSessionConfig=r),e&&t&&(n.estimatedOrderAmount={amount:e,currencyCode:t}),n}const P={method:m,url:`${C}/remote-checkout/${t}/payment-session`,extractAmazonCheckoutSessionId:g};return Object.assign(Object.assign({},S),{createCheckoutSession:P,sandbox:!!u})}isEnvironmentSpecific(e){return/^(SANDBOX|LIVE)/.test(e)}getAmazonPayV2SDK(){return this.getOrThrow(this.amazonPayV2SDK)}getButtonParentContainer(){return this.getOrThrow(this.buttonParentContainer)}getAmazonPayV2Button(){return this.getOrThrow(this.amazonPayV2Button)}getOrThrow(e){return ii(e,()=>new ri(ti.PaymentNotInitialized))}getCheckoutState(e){return"object"==typeof(t=e)&&null!==t&&"cart"in t&&"checkout"in t&&"config"in t&&"paymentMethods"in t?{getCart:e.cart.getCart,getCheckout:e.checkout.getCheckout,getStoreConfigOrThrow:e.config.getStoreConfigOrThrow,getPaymentMethodOrThrow:t=>e.paymentMethods.getPaymentMethodOrThrow(t)}:e;var t}}class mi extends Xn{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"}}class yi{constructor(e,t=window){this.scriptLoader=e,this.windowWithAmazonPay=t}load(e){return t=this,n=void 0,r=function*(){const{initializationData:t}=e,n=(null==t?void 0:t.region)||"us",i=oi[n];if(yield this.scriptLoader.loadScript(`https://static-${i}.payments-amazon.com/checkout.js`),!this.windowWithAmazonPay.amazon)throw new mi;return this.windowWithAmazonPay.amazon},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}function gi(){return new pi(new yi(a()))}function fi(e,t){return Object.assign(e,{resolveIds:t})}class vi extends Xn{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class _i extends Xn{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var Si=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ii{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return Si(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t||!(null==n?void 0:n.container))throw new vi('Unable to proceed because "methodId" or "containerId" argument is not provided.');let i;try{i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}catch(e){yield this.paymentIntegrationService.loadPaymentMethod(t),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}yield this.amazonPayV2PaymentProcessor.initialize(i),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:n.container,methodId:t,placement:si.Checkout})})}deinitialize(){return Si(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize()})}signIn(){throw new _i('In order to sign in via Amazon, the shopper must click on "Amazon Pay" button.')}signOut(e){return Si(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentId();t&&(yield this.amazonPayV2PaymentProcessor.signout(),yield this.paymentIntegrationService.remoteCheckoutSignOut(t.providerId,e))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}}const wi=fi(e=>new Ii(e,gi()),[{id:"amazonpay"}]);function Ci(e,t,n=!0){var i;return null!==(i=e[t])&&void 0!==i?i:n}const bi="3.128.0",Pi="3.123.2",Oi="3.106.0";class Ei{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()||(Ci(t,"PAYPAL-5809.braintree_hosted_fields_fix_version")?bi:Ci(t,"PAYPAL-5636.update_braintree_sdk_version")?Pi:Oi)}getPreloadedSDKVersion(){const e=this.braintreeWindow.braintree;if(e){const t=j(Object.values(e),e=>!!e.VERSION);return null==t?void 0:t.VERSION}}}class Ai extends Xn{constructor(e){super(e||"Unsupported browser error"),this.name="UnsupportedBrowserError",this.type="unsupported_browser"}}var Ti,ki,Di,Mi,zi,xi,Ni;function Ri(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"}(Ti||(Ti={})),function(e){e.Completed="COMPLETED",e.Pending="PENDING",e.Failed="FAILED"}(ki||(ki={})),function(e){e.TRUSTLY="trustly"}(Di||(Di={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="cancelled",e.UNRECOGNIZED="unrecognized"}(Mi||(Mi={})),function(e){e.Customer="CUSTOMER",e.Merchant="MERCHANT",e.Network="NETWORK",e.Internal="INTERNAL",e.Unknown="UNKNOWN"}(zi||(zi={})),function(e){e.KountNotEnabled="DATA_COLLECTOR_KOUNT_NOT_ENABLED"}(xi||(xi={})),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"}(Ni||(Ni={}));var Fi,Li,ji,Bi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ui{constructor(e){this.braintreeScriptLoader=e}initialize(e){this.setClientToken(e)}deinitialize(){return Bi(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollector),this.dataCollector=void 0})}getClient(){return Bi(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 Bi(this,void 0,void 0,function*(){const t={deviceData:void 0,teardown:()=>Promise.resolve()};if(!this.dataCollector)try{const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadDataCollector(),i=Object.assign({client:t,kount:!0},e);this.dataCollector=yield n.create(i)}catch(e){if(Ri(e)&&e.code===xi.KountNotEnabled)return t;throw e}return this.dataCollector})}getBraintreeGooglePayment(){return Bi(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 Bi(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 Bi(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment){const[t,n]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadLocalPayment()]);this.braintreeLocalPayment=yield new Promise((i,r)=>{n.create({client:t,merchantAccountId:e},(e,t)=>{e&&r(e),i(t)})})}return this.braintreeLocalPayment})}getUsBankAccount(){return Bi(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 Bi(this,void 0,void 0,function*(){return this.visaCheckoutSDK||(this.visaCheckoutSDK=yield this.braintreeScriptLoader.loadVisaCheckoutSdk(e)),this.visaCheckoutSDK})}getVenmoCheckoutOrThrow(){return Bi(this,void 0,void 0,function*(){if(!this.braintreeVenmo){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadVenmoCheckout(),n={client:e,allowDesktop:!0,paymentMethodUsage:"multi_use"},i=yield t.create(n);if(!i.isBrowserSupported())throw new Ai;this.braintreeVenmo=i}return this.braintreeVenmo})}setClientToken(e){this.clientToken=e}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ti.PaymentNotInitialized);return this.clientToken}teardownModule(e){return e?e.teardown():Promise.resolve()}}!function(e){e.Sandbox="sandbox",e.Production="production"}(Fi||(Fi={})),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"}(Li||(Li={})),function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(ji||(ji={}));const qi={[Oi]:{[Li.Client]:"sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt",[Li.PaypalCheckout]:"sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O",[Li.Paypal]:"sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+",[Li.LocalPayment]:"sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT",[Li.DataCollector]:"sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV",[Li.UsBankAccount]:"sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ",[Li.GooglePayment]:"sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe",[Li.ThreeDSecure]:"sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB",[Li.VisaCheckout]:"sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT",[Li.Venmo]:"sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov",[Li.HostedFields]:"sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy",[Li.Fastlane]:"sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa"},[Pi]:{[Li.Client]:"sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO",[Li.PaypalCheckout]:"sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/",[Li.Paypal]:"sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt",[Li.LocalPayment]:"sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH",[Li.DataCollector]:"sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO",[Li.UsBankAccount]:"sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW",[Li.GooglePayment]:"sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO",[Li.ThreeDSecure]:"sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym",[Li.VisaCheckout]:"sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS",[Li.Venmo]:"sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU",[Li.HostedFields]:"sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P",[Li.Fastlane]:"sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y"},[bi]:{[Li.Client]:"sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq",[Li.PaypalCheckout]:"sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh",[Li.Paypal]:"sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH",[Li.LocalPayment]:"sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC",[Li.DataCollector]:"sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc",[Li.UsBankAccount]:"sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F",[Li.GooglePayment]:"sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i",[Li.ThreeDSecure]:"sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D",[Li.VisaCheckout]:"sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv",[Li.Venmo]:"sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz",[Li.HostedFields]:"sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z",[Li.Fastlane]:"sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr"}};var Vi,Gi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hi{constructor(e,t,n){this.scriptLoader=e,this.braintreeHostWindow=t,this.braintreeSDKVersionManager=n}loadClient(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Client,"client.min.js")})}loadFastlane(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Fastlane,"fastlane.min.js")})}loadPaypalCheckout(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.PaypalCheckout,"paypal-checkout.min.js")})}loadPaypal(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.Paypal,"paypal.min.js")})}loadLocalPayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.LocalPayment,"local-payment.min.js")})}loadDataCollector(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.DataCollector,"data-collector.min.js")})}loadUsBankAccount(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.UsBankAccount,"us-bank-account.min.js")})}loadGooglePayment(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.GooglePayment,"google-payment.min.js")})}load3DS(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.ThreeDSecure,"three-d-secure.min.js")})}loadVisaCheckout(){return this.loadBraintreeModuleOrThrow(Li.VisaCheckout,"visa-checkout.min.js")}loadVenmoCheckout(){return this.loadBraintreeModuleOrThrow(Li.Venmo,"venmo.min.js")}loadHostedFields(){return Gi(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(Li.HostedFields,"hosted-fields.min.js")})}loadVisaCheckoutSdk(e){return Gi(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 mi;return this.braintreeHostWindow.V})})}loadBraintreeModuleOrThrow(e,t){return Gi(this,void 0,void 0,function*(){let n=this.getBraintreeModule(e);if(n)return n;const i=this.braintreeSDKVersionManager.getSDKVersion(),r=`//js.braintreegateway.com/web/${i}/js/${t}`,o=i in qi?this.getIntegrityValuesByModuleName(e,i):void 0;if(yield this.scriptLoader.loadScript(r,o?{async:!0,attributes:{integrity:o,crossorigin:"anonymous"}}:void 0),n=this.getBraintreeModule(e),!n)throw new mi;return n})}getBraintreeModule(e){var t;return null===(t=this.braintreeHostWindow.braintree)||void 0===t?void 0:t[e]}getIntegrityValuesByModuleName(e,t){const n=qi[t][e];if(!n)throw new Error("Unexpected fileName value");return n}}class Wi extends Xn{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}!function(e){e.BRAINTREE="braintree",e.BRAINTREE_FASTLANE="braintreeacceleratedcheckout"}(Vi||(Vi={}));var $i,Yi=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}($i||($i={}));class Ki{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._onAuthorizeCallback=ce,this._onError=ce,this._onClick=ce,this._subTotalLabel=$i.Subtotal,this._shippingLabel=$i.Shipping,this._hasApplePaySession=!1}initialize(e){var t;return Yi(this,void 0,void 0,function*(){const{methodId:n,applepay:i}=e;if(!n||!i)throw new ni(ei.MissingPaymentMethod);const{container:r,shippingLabel:o,subtotalLabel:a,onError:s=ce,onClick:d=ce,onPaymentAuthorize:c}=i;this._shippingLabel=o||$i.Shipping,this._subTotalLabel=a||$i.Subtotal,this._onAuthorizeCallback=c,this._onError=s,this._onClick=d;let l=this._paymentIntegrationService.getState();yield this._applePayScriptLoader.loadSdk();try{this._paymentMethod=l.getPaymentMethodOrThrow(n)}catch(e){l=yield this._paymentIntegrationService.loadPaymentMethod(n),this._paymentMethod=l.getPaymentMethodOrThrow(n)}yield this._paymentIntegrationService.verifyCheckoutSpamProtection(),this._applePayButton=this._createButton(r),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===Vi.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken)})}deinitialize(){return Promise.resolve()}signIn(){throw new _i('In order to sign in via Apple, the shopper must click on "Apple Pay" button.')}signOut(){throw new _i("Need to do signout via apple.")}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}_createButton(e){const t=document.getElementById(e);if(!t)throw new vi("Unable to create sign-in button without valid container ID.");const n=this._createApplePayButtonElement();return t.appendChild(n),n}_createApplePayButtonElement(){const e=document.createElement("apple-pay-button");return e.setAttribute("buttonstyle","black"),e.setAttribute("type","plain"),e.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),e}_handleWalletButtonClick(e){if(e.preventDefault(),this._hasApplePaySession)return;this._onClick();const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new ni(ei.MissingPaymentMethod);const o=this._getBaseRequest(n,r,i,this._paymentMethod),a=this._sessionFactory.create(o);this._handleApplePayEvents(a,this._paymentMethod,i),a.begin(),this._hasApplePaySession=!0}_getBaseRequest(e,t,n,i){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=n,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=i,u=e.lineItems.physicalItems.length>0,h={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:[],total:u?{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"pending"}:{label:a,amount:`${t.grandTotal.toFixed(d)}`,type:"final"}};if(u)null===(r=h.requiredShippingContactFields)||void 0===r||r.push("postalAddress");else{const e=[{label:this._subTotalLabel,amount:`${t.subtotal.toFixed(d)}`}];t.taxes.forEach(t=>e.push({label:t.name,amount:`${t.amount.toFixed(d)}`})),h.lineItems=e}return h}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>Yi(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){this._onError(e)}}),e.onshippingcontactselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingContactSelected(e,n,t)}),e.onshippingmethodselected=t=>Yi(this,void 0,void 0,function*(){return this._handleShippingMethodSelected(e,n,t)}),e.oncancel=()=>Yi(this,void 0,void 0,function*(){this._hasApplePaySession=!1;try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){return this._onError(new Wi)}}),e.onpaymentauthorized=n=>Yi(this,void 0,void 0,function*(){return this._onPaymentAuthorized(n,e,t)})}_handleShippingContactSelected(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const r=this._transformContactToAddress(n.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const{storeProfile:{storeName:o}}=t;let a=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:s}}=a.getCartOrThrow();let d=a.getCheckoutOrThrow();const c=null===(i=d.consignments[0].selectedShippingOption)||void 0===i?void 0:i.id,l=d.consignments[0].availableShippingOptions,u=null==l?void 0:l.find(({id:e})=>e===c),h=null==l?void 0:l.filter(e=>e.id!==c),p=u?[{label:u.description,amount:`${u.cost.toFixed(s)}`,detail:u.additionalDescription,identifier:u.id}]:[];if(h&&[...h.filter(e=>e.isRecommended),...h.filter(e=>!e.isRecommended)].forEach(e=>p.push({label:e.description,amount:`${e.cost.toFixed(s)}`,detail:e.additionalDescription,identifier:e.id})),!(l instanceof Array))throw new Error("Shipping options not available.");if(0===l.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:o,amount:`${d.grandTotal.toFixed(s)}`},[]);const m=l.find(e=>e.isRecommended),y=m?m.id:l[0].id,g=u?u.id:y;try{yield this._updateShippingOption(g)}catch(e){return this._onError(e)}a=this._paymentIntegrationService.getState(),d=a.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:o,amount:`${d.grandTotal.toFixed(s)}`},newLineItems:this._getUpdatedLineItems(d,s)})})}_handleShippingMethodSelected(e,t,n){return Yi(this,void 0,void 0,function*(){const{storeProfile:{storeName:i}}=t,{shippingMethod:{identifier:r}}=n;try{yield this._updateShippingOption(r)}catch(t){return e.abort(),this._hasApplePaySession=!1,this._onError(t)}const o=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:a}}=o.getCartOrThrow(),s=o.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:i,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_getUpdatedLineItems(e,t){const n=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>n.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),n.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),n}_updateShippingOption(e){return Yi(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return Yi(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/api/public/v1/payments/applepay/validate_merchant`,{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})})}_onPaymentAuthorized(e,t,n){var i;return Yi(this,void 0,void 0,function*(){const{token:r,billingContact:o,shippingContact:a}=e.payment,s=this._paymentIntegrationService.getState().getCartOrThrow().lineItems.physicalItems.length>0;let d;(null===(i=n.initializationData)||void 0===i?void 0:i.gateway)===Vi.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:r.paymentData,payment_method:r.paymentMethod,transaction_id:r.transactionIdentifier}}}},l=this._transformContactToAddress(o),u=this._transformContactToAddress(a),h=null==a?void 0:a.emailAddress,p=(null==a?void 0:a.phoneNumber)||"";try{return yield this._paymentIntegrationService.updateBillingAddress(Object.assign(Object.assign({},l),{email:h,phone:p})),s&&(yield this._paymentIntegrationService.updateShippingAddress(u)),yield this._paymentIntegrationService.submitOrder({useStoreCredit:!1}),yield this._paymentIntegrationService.submitPayment(c),t.completePayment(ApplePaySession.STATUS_SUCCESS),this._onAuthorizeCallback()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),this._onError(e)}})}_transformContactToAddress(e){return{firstName:(null==e?void 0:e.givenName)||"",lastName:(null==e?void 0:e.familyName)||"",city:(null==e?void 0:e.locality)||"",company:"",address1:(null==e?void 0:e.addressLines)&&e.addressLines[0]||"",address2:(null==e?void 0:e.addressLines)&&e.addressLines[1]||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||"",phone:(null==e?void 0:e.phoneNumber)||"",stateOrProvince:(null==e?void 0:e.administrativeArea)||"",stateOrProvinceCode:(null==e?void 0:e.administrativeArea)||"",customFields:[]}}_getBraintreeDeviceData(){return Yi(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}function Ji(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}class Zi{create(e){return Ji(window),new ApplePaySession(1,e)}}class Qi{constructor(e){this.scriptLoader=e,this.sdkVersion="1.latest"}loadSdk(){return e=this,t=void 0,i=function*(){(function(e){return"ApplePaySDK"in e})(window)||(yield this.scriptLoader.loadScript(`https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`),Ji(window))},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const Xi=fi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new Ki(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]);class er extends Xn{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"}}const tr={body:{},headers:{},status:0};class nr extends Xn{constructor(e,{message:t,errors:n}={}){const{body:i,headers:r,status:o}=e||tr;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=r,this.status=o,this.errors=n||[]}}var ir,rr,or,ar,sr,dr,cr;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ir||(ir={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(rr||(rr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(or||(or={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(ar||(ar={})),function(e){e.pill="pill",e.rect="rect"}(sr||(sr={})),function(e){e.OXXO="oxxo"}(dr||(dr={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(cr||(cr={}));var lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ur{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.bigCommercePaymentsRequestSender=n,this.bigCommercePaymentsScriptLoader=i}loadPayPalSdk(e,t,n,i){return lr(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.bigCommercePaymentsScriptLoader.getPayPalSDK(a,o,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return lr(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ni(ei.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return lr(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return lr(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.bigCommercePaymentsRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return lr(this,void 0,void 0,function*(){try{const{status:n}=yield this.bigCommercePaymentsRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ni(ei.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===Rt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return lr(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&ar[t]?t:void 0,height:this.getValidHeight(n),label:i&&or[i]?i:void 0,shape:r&&sr[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}const hr="This API endpoint is for internal use only and may change in the future";var pr;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(pr||(pr={}));const mr=pr,yr={"X-Checkout-SDK-Version":"1.904.2"};var gr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fr{constructor(e){this.requestSender=e}createOrder(e,t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return gr(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/bigcommerce_payments",{headers:n,body:t})).body})}getOrderStatus(e="bigcommerce_payments",t){return gr(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var vr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _r{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i){return vr(this,void 0,void 0,function*(){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n);return this.loadPayPalSDK(r,i)})}loadPayPalSDK(e,t=!1){return vr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsPayPalSDK||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.bigCommercePaymentsPayPalSDK)throw new mi;return this.window.bigCommercePaymentsPayPalSDK})}getPayPalSdkScriptConfigOrThrow(e,t,n=!0){const{id:i,clientToken:r,initializationData:o}=e;if(!(null==o?void 0:o.clientId))throw new ni(ei.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isVenmoEnabled:u,isHostedCheckoutEnabled:h,isPayPalCreditAvailable:p,isDeveloperModeApplicable:m,availableAlternativePaymentMethods:y=[],enabledAlternativePaymentMethods:g=[],isGooglePayEnabled:f}=o,v=h||n,_="bigcommerce_payments_creditcards"===i,S=_?["card"]:[],I=_?[]:["card"],w=p?["credit","paylater"]:[],C=p?[]:["credit","paylater"],b=u?["venmo"]:[],P=u?[]:["venmo"],O=y.filter(e=>!g.includes(e)),E=f?["googlepay"]:[],A=n?["card-fields"]:[],T=this.filterFundingOptions([...I,...C,...P,...O]),k=this.filterFundingOptions([...S,...w,...b,...g]);return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":k.length>0?k:void 0,"disable-funding":T.length>0?T:void 0,commit:v,components:["buttons","hosted-fields","payment-fields","legal",...E,...A],currency:t,intent:a},m&&{"buyer-country":c}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"bigCommercePaymentsPayPalSDK"}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const Sr=e=>{const{getHost:t}=e.getState();return new ur(Ee(),e,new fr(n({host:t()})),new _r(a()))},Ir=40;var wr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return wr(this,void 0,void 0,function*(){const{bigcommerce_payments:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.bigcommerce_payments.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.bigcommerce_payments.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return wr(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return wr(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()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a}=t,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:c,paymentButtonStyles:l,isAppSwitchEnabled:u=!1}=d.initializationData||{},{checkoutTopButtonStyles:h}=l||{},p=Object.assign(Object.assign(Object.assign({},u&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)}),o&&{onClick:()=>o()}),m=Object.assign(Object.assign({},!u&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,a)}),y=Object.assign(Object.assign({fundingSource:s.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},h),{height:Ir}))},p),c&&m),g=s.Buttons(y);g.isEligible()?(null===(n=g.hasReturned)||void 0===n?void 0:n.call(g))&&u?null===(i=g.resume)||void 0===i||i.call(g):g.render(`#${r}`):this.bigCommercePaymentsIntegrationService.removeElement(r)}onHostedCheckoutApprove(e,t,n,i){return wr(this,void 0,void 0,function*(){if(!e.orderID)throw new ni(ei.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const br=fi(e=>new Cr(e,Sr(e)),[{id:"bigcommerce_payments"}]);var Pr,Or,Er,Ar,Tr,kr,Dr,Mr,zr,xr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Nr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n){return xr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsFastlaneSdk){const i=this.getPayPalFastlaneSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.bigCommercePaymentsFastlaneSdk)throw new mi}return this.window.bigCommercePaymentsFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i){return xr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsGooglePay||i){const i=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.bigCommercePaymentsGooglePay)throw new mi;return this.window.bigCommercePaymentsGooglePay})}getPayPalApmsSdk(e,t){return xr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsApms){const n=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(n),!this.window.bigCommercePaymentsApms)throw new mi}return this.window.bigCommercePaymentsApms})}getPayPalMessages(e,t){return xr(this,void 0,void 0,function*(){if(!this.window.bigCommercePaymentsMessages){const n=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(n)}if(!this.window.bigCommercePaymentsMessages)throw new mi;return this.window.bigCommercePaymentsMessages})}loadPayPalSdk({options:e,attributes:t}){return xr(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,attributionId:d}=r;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","three-domain-secure"],currency:t,intent:o},attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"bigCommercePaymentsFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":i}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n=!0){const{clientToken:i,initializationData:r}=e;if(!r||!r.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||n;return{options:Object.assign({"client-id":a,"merchant-id":s,commit:h,components:["googlepay"],currency:t,intent:o},u&&{"buyer-country":d}),attributes:{"data-partner-attribution-id":c,"data-client-token":i,"data-namespace":"bigCommercePaymentsGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:i,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=n,u=this.filterFundingOptions(l),h=this.filterFundingOptions(c.filter(e=>!l.includes(e)));return{options:Object.assign({"client-id":r,"merchant-id":o,"enable-funding":u.length>0?u:void 0,"disable-funding":h.length>0?h:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:i},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"bigCommercePaymentsApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:n}=e;if(!n||!n.clientId)throw new ni(ei.MissingPaymentMethod);const{clientId:i,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=n;return{options:Object.assign({"client-id":i,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"bigCommercePaymentsMessages","data-partner-attribution-id":o}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Rr(){return new Nr(o())}!function(e){e.CVV="cvv",e.PAN="pan"}(Pr||(Pr={}));class Fr{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,n=document.cookie;let i=null;const r=n.indexOf(t);if(r>-1){let e=n.indexOf(";",r);-1===e&&(e=n.length),i=decodeURIComponent(n.substring(r+t.length,e))}return i}static set(e,t,n={secure:!0}){let i=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:r,path:o,domain:a,secure:s}=n;if(r)i+=`; expires=${r.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),i+=`; expires=${e.toUTCString()}`}o&&(i+=`; path=${o}`),a&&(i+=`; domain=${a}`),s&&(i+="; secure"),document.cookie=i}static remove(e,t){Fr.set(e,"",Object.assign({expires:new Date(0)},t))}}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Or||(Or={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(Er||(Er={})),function(e){e.Always="SCA_ALWAYS"}(Ar||(Ar={})),function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(Tr||(Tr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(kr||(kr={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Dr||(Dr={})),function(e){e.pill="pill",e.rect="rect"}(Mr||(Mr={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(zr||(zr={}));var Lr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class jr{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return Lr(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.bigCommercePaymentsFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.bigCommercePaymentsFastlane=yield e.Fastlane({styles:n||t})}return this.window.bigCommercePaymentsFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.bigCommercePaymentsFastlane)throw new mi;return this.window.bigCommercePaymentsFastlane}lookupCustomerOrThrow(e){return Lr(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return Lr(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||zr.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function Br(){return new jr}function Ur(e){return"string"!=typeof e}function qr(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Ur),o=ue(e.input,Ur),a=ue(e.toggle,Ur),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Ur),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Ur),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,f,v,_,S,I,w,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.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===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.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===(p=null==t?void 0:t.input)||void 0===p?void 0:p.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===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(f=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===f?void 0:f.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(_=null===(v=null==t?void 0:t.text)||void 0===v?void 0:v.body)||void 0===_?void 0:_.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(S=null==t?void 0:t.text)||void 0===S?void 0:S.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var Vr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gr{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsSdk=t,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){var t;return Vr(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_fastlane:i}=e;if(!n)throw new vi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(o,r.currency.code,r.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return Vr(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId()})}signOut(e){return Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return Vr(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new vi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new vi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return Vr(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===zr.CANCELED;yield this.updateCustomerDataState(e,s),d?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return Vr(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return qr(r?i:{},null==t?void 0:t.styles)}}const Hr=fi(e=>new Gr(e,Rr(),Br()),[{id:"bigcommerce_payments_fastlane"},{id:"bigcommerce_payments_creditcards"}]);var Wr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $r{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=ce}initialize(e){return Wr(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_paylater.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_paylater.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC BigCommercePayments PayLater]: button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Wr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Wr(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()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d}=a.initializationData||{},{checkoutTopButtonStyles:c}=d||{},l=Object.assign({createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)},h=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let p=!1;h.forEach(e=>{if(!p){const t=Object.assign(Object.assign({fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},c),{height:Ir}))},l),s&&u),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),p=!0)}}),p||this.bigCommercePaymentsIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Wr(this,void 0,void 0,function*(){if(!e.orderID)throw new ni(ei.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.bigCommercePaymentsIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.bigCommercePaymentsIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.bigCommercePaymentsIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Wr(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.bigCommercePaymentsIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Yr=fi(e=>new $r(e,Sr(e)),[{id:"bigcommerce_payments_paylater"}]);var Kr=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return Kr(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_venmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_venmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC Payments Venmo]: Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Kr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Kr(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()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:Ir})),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.bigCommercePaymentsIntegrationService.removeElement(n)}}const Zr=fi(e=>new Jr(e,Sr(e)),[{id:"bigcommerce_payments_venmo"}]);class Qr extends Xn{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"}}class Xr extends nr{constructor(e){super(e,{message:"There is a problem processing your payment. Please try again later."}),this.name="PaymentMethodInvalidError",this.type="payment_method_invalid"}}var eo,to,no,io=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ro{constructor(e,t){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=window}initialize(e){var t;return io(this,void 0,void 0,function*(){const{methodId:n,bolt:i}=e,{onInit:r}=i||{};if(!n)throw new vi('Unable to proceed because "methodId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);if(!(null===(t=o.initializationData)||void 0===t?void 0:t.publishableKey))throw new ni(ei.MissingPaymentMethod);const{developerConfig:a,publishableKey:s}=o.initializationData;if(yield this.boltScriptLoader.loadBoltClient(s,o.config.testMode,a),r&&"function"==typeof r){const e=this.getCustomerEmail();r(yield this.hasBoltAccount(e),e)}})}deinitialize(){return Promise.resolve()}signIn(e,t){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return io(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){return io(this,void 0,void 0,function*(){const{continueWithCheckoutCallback:t=w,checkoutPaymentMethodExecuted:n,methodId:i}=e||{},r=this.getCustomerEmail();if(!i)throw new vi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof t)throw new vi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(r)return this.openBoltCheckoutModalOrThrow(r,i,t,n);t()})}openBoltCheckoutModalOrThrow(e,t,n,i){var r;return io(this,void 0,void 0,function*(){const o=this.getBoltClientOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethod(t);try{if(null===(r=null==a?void 0:a.initializationData)||void 0===r?void 0:r.embeddedOneClickEnabled){const t=yield this.hasBoltAccount(e);if(t){const t={close:()=>{n()}};yield o.openCheckout(e,t)}else n();"function"==typeof i&&i({hasBoltAccount:t})}else n()}catch(e){if(function(e){return"string"==typeof e.message&&"string"==typeof e.type&&("string"==typeof e.subtype||!e.subtype)&&e instanceof Error}(e)&&"MissingDataError"!==e.name&&"NotInitializedError"!==e.name)throw new Qr(e.message);throw e}})}getBoltClientOrThrow(){const e=this.boltHostWindow.BoltCheckout;if(!e)throw new ri(ti.PaymentNotInitialized);return e}hasBoltAccount(e){return io(this,void 0,void 0,function*(){const t=this.getBoltClientOrThrow();try{return yield t.hasBoltAccount(e)}catch(e){throw new Xr}})}getCustomerEmail(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress();return(null==t?void 0:t.email)||(null==n?void 0:n.email)||""}}!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(eo||(eo={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(to||(to={})),function(e){e.Pill="pill",e.Rect="rect"}(no||(no={}));var oo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ao{constructor(e,t=window){this.scriptLoader=e,this.boltHostWindow=t}loadBoltClient(e,t,n,i,r){return oo(this,void 0,void 0,function*(){if(this.boltHostWindow.BoltCheckout)return this.boltHostWindow.BoltCheckout;if(!e)throw new vi('Unable to initialize payment because "publishableKey" argument is not provided.');if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/connect-bigcommerce.js`,this.getScriptOptions("bolt-connect",e,i,r)),yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/track.js`,this.getScriptOptions("bolt-track",e)),!this.boltHostWindow.BoltCheckout)throw new mi;return this.boltHostWindow.BoltCheckout})}loadBoltEmbedded(e,t,n){return oo(this,void 0,void 0,function*(){if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,n)}/embed.js`,{async:!0,attributes:{id:"bolt-embedded"}}),!this.boltHostWindow.Bolt)throw new mi;return this.boltHostWindow.Bolt(e)})}getDomainURL(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case eo.StagingMode:return"connect-staging.bolt.com";case eo.DevelopmentMode:return`connect.${t.developerDomain}`}return"connect-sandbox.bolt.com"}getScriptOptions(e,t,n,i){return{async:!0,attributes:Object.assign(Object.assign({id:e,"data-publishable-key":t},n&&{"data-shopping-cart-id":n}),i&&{"data-storefront-api-token":i})}}}const so=fi(e=>new ro(e,new ao(a())),[{id:"bolt"}]);class co extends vi{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"}}class lo extends Xn{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"}}let uo=null;const ho=["buttons","messages"];var po,mo,yo,go,fo,vo;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(po||(po={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(mo||(mo={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(yo||(yo={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(go||(go={})),function(e){e.PILL="pill",e.RECT="rect"}(fo||(fo={})),function(e){e.CART="cart",e.HOME="homepage",e.PAYMENT="payment",e.PRODUCT="product"}(vo||(vo={}));var _o=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class So{constructor(e,t,n){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.overlay=n,this.dataCollectors={}}initialize(e,t){this.clientToken=e,this.threeDSecureOptions=t}getBraintreeFastlane(e,t,n){return _o(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(),i=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:i,deviceData:r,styles:n||a})}return this.braintreeHostWindow.braintreeFastlane})}getClient(){return _o(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,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["shouldSaveInstrument"]);const i=Ae();return this.getPaypal().then(e=>{var r;return i&&(null===(r=this.overlay)||void 0===r||r.show({onClick:()=>e.focusWindow()})),e.tokenize(Object.assign({enableShippingAddress:!0,flow:t?"vault":"checkout",useraction:"commit"},n))}).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,n){return _o(this,void 0,void 0,function*(){const i=yield this.getClient(),r=yield this.braintreeScriptLoader.loadPaypalCheckout(),o={client:i};return this.paypalCheckout=yield r.create(o,(i,r)=>{var o;if(i)return n(i);const a=Object.assign(Object.assign({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:ho.toString(),intent:e.intent,commit:null===(o=e.commit)||void 0===o||o});this.braintreeHostWindow.paypal?t(r):function(e,t){return uo||(uo=new Promise((n,i)=>{e.loadPayPalSDK(t,t=>{t?(uo=null,i(t)):n(e)})})),uo}(r,a).then(()=>t(r))}),this.paypalCheckout})}getDataCollector(e){return _o(this,void 0,void 0,function*(){const t=(null==e?void 0:e.paypal)?"paypal":"default";let n=this.dataCollectors[t];if(!n){try{const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadDataCollector(),r=Object.assign({client:t,kount:!0},e);n=yield i.create(r)}catch(e){if(!Ri(e)||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==e.code)throw e;n={deviceData:void 0,teardown:()=>Promise.resolve()}}this.dataCollectors[t]=n}return n})}getBraintreeEnv(e=!1){return e?Fi.Sandbox:Fi.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:n,shippingAddress:i}=e,r=(null==i?void 0:i.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:n,address_line_1:null==i?void 0:i.line1,address_line_2:null==i?void 0:i.line2,city:null==i?void 0:i.city,state:null==i?void 0:i.state,country_code:null==i?void 0:i.countryCode,postal_code:null==i?void 0:i.postalCode}}mapToLegacyBillingAddress(e){const{billingAddress:t,email:n,firstName:i,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:n,first_name:i,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 _o(this,void 0,void 0,function*(){const{deviceData:t}=yield this.getDataCollector({riskCorrelationId:e});return t})}teardown(){return _o(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 _o(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 _o(this,void 0,void 0,function*(){if(!this.venmoCheckout){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadVenmoCheckout(),i=Object.assign({client:t,allowDesktop:!0,paymentMethodUsage:"multi_use"},e||{});this.venmoCheckout=yield new Promise((e,t)=>{n.create(i,(n,i)=>n?t(n):i.isBrowserSupported()?void e(i):t(new Ai))})}return this.venmoCheckout})}verifyCard(e,t,n){return _o(this,void 0,void 0,function*(){const i=yield this.tokenizeCard(e,t);return this.challenge3DSVerification(i,n)})}tokenizeCard(e,t){return _o(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 co(["payment.paymentData"]);const i=this.getErrorsRequiredFields(n);if(!$(i))throw new lo(i);const r=this.mapToCreditCard(n,t),o=yield this.getClient(),{creditCards:a}=yield o.request(r);return{nonce:a[0].nonce,bin:a[0].details.bin}})}challenge3DSVerification(e,t){return _o(this,void 0,void 0,function*(){const n=yield this.get3DS();return this.present3DSChallenge(n,t,e)})}teardownModule(e){return e?e.teardown():Promise.resolve()}getClientTokenOrThrow(){if(!this.clientToken)throw new ri(ti.PaymentNotInitialized);return this.clientToken}getErrorsRequiredFields(e){const{ccNumber:t,ccExpiry:n}=e,i={};return t||(i.ccNumber=[{message:"Credit card number is required",type:"required"}]),n||(i.ccExpiry=[{message:"Expiration date is required",type:"required"}]),i}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,n){const{nonce:i,bin:r}=n;if(!this.threeDSecureOptions||!i)throw new ri(ti.PaymentNotInitialized);const{addFrame:o,removeFrame:a,challengeRequested:s=!0,additionalInformation:d}=this.threeDSecureOptions,c=()=>_o(this,void 0,void 0,function*(){const t=yield e.cancelVerifyCard();return u.cancel(new Wi),t}),l=t.toFixed(2),u=new An(e.verifyCard({addFrame:(e,t)=>{o&&o(e,t,c)},amount:Number(l),bin:r,challengeRequested:s,nonce:i,removeFrame:a,onLookupComplete:(e,t)=>{t()},collectDeviceData:!0,additionalInformation:d}));return u.promise}}var Io=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class wo{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return Io(this,void 0,void 0,function*(){const{braintreepaypal:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ni(ei.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ni(ei.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),u)},e=>this.handleError(e,i,r))})}deinitialize(){return Io(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return Io(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Io(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,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow,d=null==s?void 0:s.FUNDING.PAYPAL;if(s&&d){const c=s.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(i),fundingSource:d,style:Object.assign(Object.assign({},r),{height:Ir}),createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});c.isEligible()&&c.render(`#${o}`)}else this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return Io(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(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!1,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return Io(this,void 0,void 0,function*(){try{const{deviceData:i}=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:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Co=fi(e=>{const t=window,n=new Ei(e),i=new So(new Hi(a(),t,n),t);return new wo(e,Ee(),i,t)},[{id:"braintreepaypal"}]);var bo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Po{constructor(e,t,n,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=i}initialize(e){return bo(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,methodId:n}=e,{container:i,onError:r}=t||{};if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.braintreepaypalcredit.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(n),!o.clientToken)throw new ni(ei.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(n),o=a.getPaymentMethodOrThrow(n)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new ni(ei.MissingPaymentMethod);const h={currency:a.getCartOrThrow().currency.code,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{this.renderPayPalButton(e,t,n,Boolean(d.testMode),Object.assign(Object.assign({},u),{height:Ir}))},e=>this.handleError(e,i,r))})}deinitialize(){return bo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return bo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return bo(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,n,i,r){const{container:o,onClick:a=ce}=t,{paypal:s}=this.braintreeHostWindow;let d=!1;s&&[s.FUNDING.PAYLATER,s.FUNDING.CREDIT].forEach(c=>{if(!d){const l=s.Buttons({env:i?"sandbox":"production",fundingSource:c,style:r,createOrder:()=>this.setupPayment(e,t,n),onApprove:i=>this.tokenizePayment(i,e,n,t),onClick:a});l.isEligible()&&(l.render(`#${o}`),d=!0)}}),s&&d||this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,n){var i;return bo(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(n),d=null==a?void 0:a.addresses[0],c=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:c,amount:r,currency:o,offerCredit:!0,intent:null===(i=s.initializationData)||void 0===i?void 0:i.intent})}catch(e){const{container:n,onError:i}=t;this.handleError(e,n,i)}})}tokenizePayment(e,t,n,i){return bo(this,void 0,void 0,function*(){try{const{deviceData:i}=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:n,action:"set_external_checkout",nonce:a,device_data:i,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:n}=i;this.handleError(e,t,n)}})}handleError(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ri(e))throw e;n(e)}}const Oo=fi(e=>{const t=window,n=new Ei(e),i=new So(new Hi(a(),t,n),t);return new Po(e,Ee(),i,t)},[{id:"braintreepaypalcredit"}]);function Eo(e){return"string"!=typeof e}function Ao(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,Eo),o=ue(e.input,Eo),a=ue(e.toggle,Eo),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,Eo),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,Eo),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,f,v,_,S,I,w,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.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===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.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===(p=null==t?void 0:t.input)||void 0===p?void 0:p.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===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(f=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===f?void 0:f.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(_=null===(v=null==t?void 0:t.text)||void 0===v?void 0:v.body)||void 0===_?void 0:_.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(S=null==t?void 0:t.text)||void 0===S?void 0:S.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var To=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ko{constructor(e,t){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.isAcceleratedCheckoutEnabled=!1}initialize({methodId:e,braintreefastlane:t}){var n;return To(this,void 0,void 0,function*(){if(!e)throw new vi('Unable to proceed because "methodId" argument is not provided.');const i=yield this.getValidPaymentMethodOrThrow(e),{isAcceleratedCheckoutEnabled:r,isFastlaneStylingEnabled:o}=i.initializationData||{},a=o?null===(n=i.initializationData)||void 0===n?void 0:n.fastlaneStyles:void 0;this.isAcceleratedCheckoutEnabled=!!r;try{if(this.isAcceleratedCheckoutEnabled){const e=Ao(a,null==t?void 0:t.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(i.id,e)}}catch(e){}return Promise.resolve()})}deinitialize(){return To(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return To(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return To(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n}=e||{};if("function"!=typeof n)throw new vi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');const i=this.paymentIntegrationService.getState().getCustomerOrThrow();if(this.isAcceleratedCheckoutEnabled&&i.isGuest){const e=yield this.shouldRunAuthenticationFlow();t&&"function"==typeof t&&t(),e&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(void 0,!0))}n()})}shouldRunAuthenticationFlow(){var e;return To(this,void 0,void 0,function*(){const t="braintreeacceleratedcheckout";try{yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t);return(null===(e=n.initializationData)||void 0===e?void 0:e.shouldRunAcceleratedCheckout)||!1}catch(e){return!1}})}getValidPaymentMethodOrThrow(e){return To(this,void 0,void 0,function*(){let t=e;try{yield this.paymentIntegrationService.loadPaymentMethod(t)}catch(n){t="braintree"===e?"braintreeacceleratedcheckout":"braintree",yield this.paymentIntegrationService.loadPaymentMethod(t)}return this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)})}}var Do=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mo{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}getDeviceSessionId(){return Do(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 Do(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getCart(),{clientToken:r,config:o}=n.getPaymentMethodOrThrow(e);if(!r)throw new ni(ei.MissingPaymentMethod);this.methodId=e,this.braintreeIntegrationService.initialize(r),this.braintreeFastlane=yield this.braintreeIntegrationService.getBraintreeFastlane(null==i?void 0:i.id,o.testMode,t)})}getBraintreeFastlaneOrThrow(){if(!this.braintreeFastlane)throw new mi;return this.braintreeFastlane}getBraintreeFastlaneComponentOrThrow(){return this.getBraintreeFastlaneOrThrow().FastlaneCardComponent}runPayPalAuthenticationFlowOrThrow(e,t){var n;return Do(this,void 0,void 0,function*(){try{const i=this.getMethodIdOrThrow(),r=this.getBraintreeFastlaneOrThrow(),{lookupCustomerByEmail:o,triggerAuthenticationFlow:a}=r.identity,s=this.paymentIntegrationService.getState(),d=s.getCartOrThrow(),c=s.getCustomer(),l=s.getBillingAddress(),{isFastlaneShippingOptionAutoSelectEnabled:u}=s.getPaymentMethodOrThrow(i).initializationData||{},h=e||(null==c?void 0:c.email)||(null==l?void 0:l.email)||"",{customerContextId:p}=yield o(h);if(!p)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:Mi.UNRECOGNIZED,addresses:[],instruments:[]}),void this.saveSessionIdToCookies(d.id);const{authenticationState:m,profileData:y}=yield a(p),g=(null===(n=null==y?void 0:y.shippingAddress)||void 0===n?void 0:n.phoneNumber)||"";if(m===Mi.CANCELED)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:[],instruments:[]}),void this.removeSessionIdFromCookies();const f=this.mapPayPalToBcAddress([y.shippingAddress],[g])||[],v=this.getPayPalBillingAddresses(y),_=v?this.mapPayPalToBcAddress([v],[g]):[],S=y.card?this.mapPayPalToBcInstrument(i,[y.card]):[],I=this.mergeShippingAndBillingAddresses(f,_);if(this.saveSessionIdToCookies(d.id),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:I,instruments:S}),_.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateBillingAddress(_[0])),_.length>0&&d.lineItems.digitalItems.length>0&&0===d.lineItems.physicalItems.length){const{firstName:e,lastName:t}=I[0],n=Object.assign(Object.assign({},_[0]),{firstName:e,lastName:t});yield this.paymentIntegrationService.updateBillingAddress(n)}f.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateShippingAddress(f[0]),t&&u&&(yield this.setShippingOption()))}catch(e){}})}getSessionIdFromCookies(){return Fr.get("bc-fastlane-sessionId")||""}saveSessionIdToCookies(e){const t=new Date;t.setDate(t.getDate()+14),Fr.set("bc-fastlane-sessionId",e,{expires:t,secure:!0})}removeSessionIdFromCookies(){Fr.remove("bc-fastlane-sessionId")}mapPayPalToBcInstrument(e,t){if(t)return t.map(t=>{const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a,binDetails:s}=i.card,[d,c]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:c,expiryYear:d,iin:(null==s?void 0:s.bin)||"",last4:a,method:e,provider:e,trustedShippingAddress:!1,type:"card",untrustedShippingCardVerificationMode:Pr.PAN}})}mapPayPalToBcAddress(e,t){if(!e)return[];const n=this.paymentIntegrationService.getState().getCountries()||[],i=e=>{const t=n.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:i(e.countryCodeAlpha2),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:t&&t[0]||"",customFields:[]}))}getPayPalBillingAddresses(e){const{card:t,name:n}=e||{};if(!t)return;const{firstName:i,lastName:r}=t.paymentSource.card.billingAddress,{firstName:o,lastName:a}=n||{},{shippingAddress:s}=e||{},d=Object.assign(Object.assign({},t.paymentSource.card.billingAddress),{firstName:i||o,lastName:r||a});return s&&Y(this.normalizeAddress(d),this.normalizeAddress(s))?s:d}normalizeAddress(e){return le(e,["id"])}mergeShippingAndBillingAddresses(e,t){const n=t.filter(t=>!e.some(e=>Y(this.normalizeAddress(e),this.normalizeAddress(t))));return[...e,...n]}getMethodIdOrThrow(){if(!this.methodId)throw new vi('Unable to proceed because "methodId" argument is not provided.');return this.methodId}setShippingOption(){var e;return Do(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getConsignments()||[],n=(null===(e=t[0])||void 0===e?void 0:e.availableShippingOptions)||[],i=n.find(e=>e.isRecommended);if(i||n.length){const e=i||n[0];yield this.paymentIntegrationService.selectShippingOption(e.id)}})}}const zo=fi(e=>{const t=window,n=new Ei(e),i=new So(new Hi(a(),t,n),t),r=new Mo(e,i);return new ko(e,r)},[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);var xo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class No{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n,this.buttonClassName="visa-checkout-wrapper",this.onError=ce}initialize(e){return xo(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!n)throw new vi('Unable to proceed because "methodId" argument is not provided.');if(!t)throw new vi('Unable to proceed because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getCheckoutOrThrow(),{clientToken:o,config:a}=i.getPaymentMethodOrThrow(n),s=i.getStoreConfigOrThrow();if(!o)throw new ni(ei.MissingPaymentMethod);this.braintreeSdk.initialize(o);const d=yield this.braintreeSdk.getBraintreeVisaCheckout(),c=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),{container:l,onError:u}=t;this.onError=u||ce;const h=d.createInitOptions({paymentRequest:{currencyCode:s.currency.code,subtotal:String(r.subtotal)},settings:{locale:s.storeProfile.storeLanguage,shipping:{collectShipping:!0}}}),p=this.createSignInButton(l,this.buttonClassName);yield c.init(h),c.on("payment.success",e=>this.tokenizePayment(d,e).then(()=>this.paymentIntegrationService.loadCheckout()).catch(e=>this.handleError(e))),c.on("payment.error",(e,t)=>this.handleError(t)),p.style.visibility="visible"})}deinitialize(){return xo(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}signIn(){throw new _i('In order to sign in via VisaCheckout, the shopper must click on "Visa Checkout" button.')}signOut(e){return xo(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 xo(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{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,i)),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 n=document.querySelector(`#${e}`);if(!n)throw new Error("Unable to proceed because the provided container ID is not valid.");return this.insertVisaCheckoutButton(n,t)}insertVisaCheckoutButton(e,t){const n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.visibility="hidden",n.style.width="max-content",n.className=t,n.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(n),n}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Ro=fi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new No(e,Ee(),i)},[{id:"braintreevisacheckout"}]);class Fo{constructor(e){if(!e)throw new Error("Currency settings missing");const{decimalPlaces:t,symbolLocation:n,symbol:i,thousandsSeparator:r,decimalSeparator:o}=e;if("string"!=typeof n||"string"!=typeof i||"string"!=typeof r||"string"!=typeof o||"string"!=typeof t)throw new vi("Invalid currency settings provided");this._decimalPlaces=parseInt(t,10),this._symbolLocation=n,this._symbol=i,this._thousandsSeparator=r,this._decimalSeparator=o}format(e){if("number"!=typeof e)throw new vi("Invalid amount provided");const t=this._formatNumber(e),n=this._formatCurrency(t);return e<0?`-${n}`:n}_formatNumber(e){const t=Math.abs(e),[n,i=""]=this._toFixed(t,this._decimalPlaces).split("."),r=n.replace(/\B(?=(\d{3})+(?!\d))/g,this._thousandsSeparator);return this._decimalPlaces<1?r:[r,i].join(this._decimalSeparator)}_formatCurrency(e){return"left"===this._symbolLocation.toLowerCase()?`${this._symbol}${e}`:`${e}${this._symbol}`}_toFixed(e,t){return(+`${Math.round(+`${e}e${t}`)}e${-t}`).toFixed(t)}}let Lo=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};Lo=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],Lo);const jo=Lo,Bo=(e,t)=>!!e&&(!!e.lineItems.physicalItems.some(e=>e.isShippingRequired)||!(!t||!e.lineItems.customItems)&&e.lineItems.customItems.length>0);function Uo(){if("undefined"==typeof window)return!1;if(function(e){return"ReactNativeWebView"in e}(window))return!0;const e=navigator.userAgent||navigator.vendor||(function(e){return"opera"in e}(window)?window.opera:""),t=/android.+; wv/i.test(e),n=/iPhone|iPod|iPad/i.test(e)&&/AppleWebKit/i.test(e)&&!/Safari/i.test(e);return t||n}var qo,Vo,Go,Ho,Wo,$o,Yo,Ko,Jo;function Zo(e){return e in $o}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(qo||(qo={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Vo||(Vo={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Go||(Go={})),function(e){e.pill="pill",e.rect="rect"}(Ho||(Ho={})),function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Wo||(Wo={})),function(e){e.AMEX="AMEX",e.DISCOVER="DISCOVER",e.INTERAC="INTERAC",e.JCB="JCB",e.MC="MASTERCARD",e.VISA="VISA"}($o||($o={})),function(e){e.OFFER="OFFER",e.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.SHIPPING_OPTION="SHIPPING_OPTION"}(Yo||(Yo={})),function(e){e.OFFER_INVALID="OFFER_INVALID",e.PAYMENT_DATA_INVALID="PAYMENT_DATA_INVALID",e.SHIPPING_ADDRESS_INVALID="SHIPPING_ADDRESS_INVALID",e.SHIPPING_ADDRESS_UNSERVICEABLE="SHIPPING_ADDRESS_UNSERVICEABLE",e.SHIPPING_OPTION_INVALID="SHIPPING_OPTION_INVALID",e.OTHER_ERROR="OTHER_ERROR"}(Ko||(Ko={})),function(e){e.INITIALIZE="INITIALIZE",e.SHIPPING_OPTION="SHIPPING_OPTION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.OFFER="OFFER"}(Jo||(Jo={}));var Qo,Xo=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ea{constructor(e,t){this._gatewayIdentifier=e,this._paymentIntegrationService=t,this._isBuyNowFlow=!1,this._shouldRequestShipping=!0,this._isWebViewExperimentOn=null}mapToShippingAddressRequestBody({shippingAddress:e}){if(!e)return;const{company:t="",phone:n=""}=this._paymentIntegrationService.getState().getShippingAddress()||{};return this._mapToAddressRequestBody(e,t,n)}mapToBillingAddressRequestBody(e){const{billingAddress:t}=e.paymentMethodData.info;if(!t)return;const{company:n="",phone:i="",email:r,customFields:o=[]}=this._paymentIntegrationService.getState().getBillingAddress()||{};return Object.assign(Object.assign({},this._mapToAddressRequestBody(t,n,i,o)),{email:r||e.email})}mapToExternalCheckoutData(e){var t;const{paymentMethodData:{tokenizationData:{token:n},info:{cardNetwork:i,cardDetails:r}}}=e;if(!n)throw new ni(ei.MissingPaymentToken);return Promise.resolve(Object.assign({nonce:n,card_information:{type:i,number:r}},this._isBuyNowFlow&&{cart_id:null===(t=this._paymentIntegrationService.getState().getCart())||void 0===t?void 0:t.id}))}getRequiredData(){var e;return Xo(this,void 0,void 0,function*(){const t={emailRequired:!0};if(!this._isShippingAddressRequired())return t;const n=yield this._paymentIntegrationService.loadShippingCountries(),i=null===(e=n.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code);return Object.assign(Object.assign({},t),{shippingAddressRequired:!0,shippingAddressParameters:Object.assign({phoneNumberRequired:!0},i&&{allowedCountryCodes:i}),shippingOptionRequired:!0})})}getCallbackIntents(){return this._isShippingAddressRequired()?[Yo.OFFER,Yo.SHIPPING_ADDRESS,Yo.SHIPPING_OPTION]:[Yo.OFFER]}getCallbackTriggers(){return{availableTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS,Jo.SHIPPING_OPTION,Jo.OFFER],initializationTrigger:[Jo.INITIALIZE],addressChangeTriggers:[Jo.INITIALIZE,Jo.SHIPPING_ADDRESS],shippingOptionsChangeTriggers:[Jo.SHIPPING_OPTION],offerChangeTriggers:[Jo.OFFER]}}getNonce(e){var t;const n=null===(t=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.nonce;if(!n)throw new ni(ei.MissingPaymentToken);return Promise.resolve(n)}extraPaymentData(){return Promise.resolve(void 0)}getMerchantInfo(){const{googleMerchantName:e,googleMerchantId:t,platformToken:n}=this.getGooglePayInitializationData();return{merchantName:e,merchantId:t,authJwt:n}}getTransactionInfo(){let e;const{getCartOrThrow:t}=this._paymentIntegrationService.getState();e=this._isBuyNowFlow?this._getCurrencyCodeOrThrow():t().currency.code;const n=this.getGooglePayInitializationData().storeCountry;if(this.isWebViewWithRestrictions()){const t=this.getTotalPrice();return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPrice:t,totalPriceStatus:Wo.ESTIMATED})}return Object.assign(Object.assign({},n&&{countryCode:n}),{currencyCode:e,totalPriceStatus:Wo.ESTIMATED,totalPrice:"0"})}isWebViewWithRestrictions(){return null!==this._isWebViewExperimentOn?this._isWebViewExperimentOn&&Uo():Uo()}setIsWebViewExperimentOn(e){this._isWebViewExperimentOn=e}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData().gatewayMerchantId;if(!e)throw new vi("Unable to proceed, gatewayMerchantId is missing.");return{gateway:this._gatewayIdentifier,gatewayMerchantId:e}}getCardParameters(){return{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.getPaymentMethod().supportedCards.filter(Zo).map(e=>$o[e]),billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!0}}}initialize(e,t,n){return this._getPaymentMethodFn=e,this._isBuyNowFlow=Boolean(t),this._currencyCode=n,this._isBuyNowFlow&&this._getCurrencyCodeOrThrow(),Promise.resolve()}handleShippingAddressChange(e){var t,n,i,r;return Xo(this,void 0,void 0,function*(){e&&(e.name=e.name||"",e.address1=e.address1||"");const o=this.mapToShippingAddressRequestBody({shippingAddress:e});o&&(yield this._paymentIntegrationService.updateShippingAddress(o));const a=this._paymentIntegrationService.getState(),s=a.getConsignments();if(!(null==s?void 0:s[0]))return;const d=s[0],c=a.getStoreConfigOrThrow();this._currencyService||(this._currencyService=new jo(c));const l=(d.availableShippingOptions||[]).map(this._getGooglePayShippingOption.bind(this)),u=null===(t=d.availableShippingOptions)||void 0===t?void 0:t.find(e=>e.isRecommended);if(l.length){const e=(null===(n=d.selectedShippingOption)||void 0===n?void 0:n.id)||(null==u?void 0:u.id)||(null===(i=l[0])||void 0===i?void 0:i.id);return!(null===(r=d.selectedShippingOption)||void 0===r?void 0:r.id)&&l[0]&&(yield this.handleShippingOptionChange((null==u?void 0:u.id)||l[0].id)),{defaultSelectedOptionId:e,shippingOptions:l}}})}handleShippingOptionChange(e){return Xo(this,void 0,void 0,function*(){if("shipping_option_unselected"!==e)return this._paymentIntegrationService.selectShippingOption(e)})}getTotalPrice(){const{getCheckoutOrThrow:e,getCartOrThrow:t,getStoreConfigOrThrow:n}=this._paymentIntegrationService.getState(),{decimalPlaces:i}=t().currency,r=Ci(n().checkoutSettings.features,"PI-5075.google_pay_round_total_price_to_max_2_decimal_places")?Math.min(i,2):i;return ge(e().outstandingBalance,r).toFixed(r)}handleCoupons(e){return Xo(this,void 0,void 0,function*(){const{redemptionCodes:t=[]}=e,{offers:n}=this.getAppliedCoupons()||{};let i;return yield t.reduce((e,t)=>Xo(this,void 0,void 0,function*(){if(yield e,(n||[]).some(({redemptionCode:e})=>e===t))return;const r=yield this.applyCoupon(t);r&&(i=r)}),Promise.resolve()),yield(n||[]).reduce((e,n)=>Xo(this,void 0,void 0,function*(){yield e,t.includes(n.redemptionCode)||(yield this._paymentIntegrationService.removeCoupon(n.redemptionCode))}),Promise.resolve()),{newOfferInfo:this.getAppliedCoupons(),error:i}})}getAppliedCoupons(){const e=this._paymentIntegrationService.getState(),{coupons:t}=e.getCheckout()||{};return{offers:(t||[]).map(e=>{const{displayName:t,code:n}=e;return{redemptionCode:n,description:t}})}}applyCoupon(e){return Xo(this,void 0,void 0,function*(){let t;try{yield this._paymentIntegrationService.applyCoupon(e)}catch(e){return e instanceof Error&&(t={reason:Ko.OFFER_INVALID,message:e.message,intent:Jo.OFFER}),t}})}setShouldRequestShipping(e){this._shouldRequestShipping=e}getGooglePayInitializationData(){return ii(this.getPaymentMethod().initializationData,()=>new vi("Missing initialization data."))}getPaymentMethod(){return ii(this._getPaymentMethodFn,()=>new ri(ti.PaymentNotInitialized))()}getGatewayIdentifier(){return this._gatewayIdentifier}setGatewayIdentifier(e){this._gatewayIdentifier=e||this.getGatewayIdentifier()}_isShippingAddressRequired(){const{getCartOrThrow:e,getStoreConfigOrThrow:t,getShippingAddress:n}=this._paymentIntegrationService.getState(),i=t();let r;return r=Ci(i.checkoutSettings.features,"PI-4290.google_pay_require_shipping_address")?this._shouldRequestShipping:void 0===n(),r&&Bo(e(),i)}_mapToAddressRequestBody(e,t,n,i){const{name:r,address1:o,address2:a,address3:s,locality:d,administrativeArea:c,countryCode:l,postalCode:u,phoneNumber:h}=e,[p,m]=this._getFirstAndLastName(r);return{firstName:p,lastName:m,company:t,address1:o,address2:`${a} ${s}`.trim(),city:d||c,stateOrProvince:c,stateOrProvinceCode:c,countryCode:l,postalCode:u,phone:h||n,customFields:i||[]}}_getFirstAndLastName(e){const t=e.split(" ");return 1===t.length?[e,""]:[t.slice(0,-1).join(" "),t[t.length-1]]}_getCurrencyCodeOrThrow(){return ii(this._currencyCode,()=>new vi('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}_getGooglePayShippingOption({id:e,cost:t,description:n,additionalDescription:i}){var r;return{id:e,label:`${(null===(r=this._currencyService)||void 0===r?void 0:r.toCustomerCurrency(t))||t} ${n}`,description:i}}}function ta(e){return"object"==typeof e&&null!==e&&"statusCode"in e}function na(e){return Object.values(Qo).includes(e)}!function(e){e.ADYEN_V2="googlepayadyenv2",e.ADYEN_V3="googlepayadyenv3",e.AUTHORIZE_NET="googlepayauthorizenet",e.BNZ="googlepaybnz",e.BRAINTREE="googlepaybraintree",e.PAYPAL_COMMERCE="googlepaypaypalcommerce",e.BIGCOMMERCE_PAYMENTS="googlepay_bigcommerce_payments",e.CHECKOUT_COM="googlepaycheckoutcom",e.CYBERSOURCE_V2="googlepaycybersourcev2",e.ORBITAL="googlepayorbital",e.STRIPE="googlepaystripe",e.STRIPE_UPE="googlepaystripeupe",e.STRIPE_OCS="googlepaystripeocs",e.WORLDPAY_ACCESS="googlepayworldpayaccess",e.TD_ONLINE_MART="googlepaytdonlinemart"}(Qo||(Qo={}));var ia=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ra{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,n;return ia(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new vi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!i)throw new vi("Unable to proceed without valid options.");let r,o=this._paymentIntegrationService.getState();try{r=o.getPaymentMethodOrThrow(this._getMethodId())}catch(e){o=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),r=o.getPaymentMethodOrThrow(this._getMethodId())}try{this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(t=r.initializationData)||void 0===t?void 0:t.isWebViewExperimentOn)),yield this._googlePayPaymentProcessor.initialize(()=>r,this._getGooglePayClientOptions(null===(n=r.initializationData)||void 0===n?void 0:n.storeCountry))}catch(e){return}this._addPaymentButton(i)})}signIn(){return Promise.reject(new _i('In order to sign in via Google Pay, the shopper must click on "Google Pay" button.'))}signOut(){var e;return ia(this,void 0,void 0,function*(){const t=null===(e=this._paymentIntegrationService.getState().getPaymentId())||void 0===e?void 0:e.providerId;t&&(yield this._googlePayPaymentProcessor.signOut(t))})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,shippingAddress:n,shippingOptionData:i,offerData:r})=>ia(this,void 0,void 0,function*(){const{availableTriggers:o,addressChangeTriggers:a,shippingOptionsChangeTriggers:s,offerChangeTriggers:d}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!o.includes(t))return;const c=a.includes(t)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(n):void 0;s.includes(t)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(i.id));const{newOfferInfo:l,error:u}=d.includes(t)?yield this._googlePayPaymentProcessor.handleCoupons(r):{},h=u;yield this._paymentIntegrationService.loadCheckout();const p=this._googlePayPaymentProcessor.getTotalPrice(),{code:m}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:m,totalPriceStatus:Wo.FINAL,totalPrice:p})},c&&{newShippingOptionParameters:c}),l&&{newOfferInfo:l}),h&&{error:h})})}}}_addPaymentButton({container:e,buttonColor:t,buttonType:n,onClick:i,onError:r}){var o;this._paymentButton=null!==(o=this._paymentButton)&&void 0!==o?o:this._googlePayPaymentProcessor.addPaymentButton(e,{buttonColor:null!=t?t:"default",buttonType:null!=n?n:"plain",onClick:this._handleClick(r,i)})}_handleClick(e,t){return n=>ia(this,void 0,void 0,function*(){n.preventDefault(),t&&"function"==typeof t&&t();try{yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let n=t;if(ta(t)){if("CANCELED"===t.statusCode)throw new Wi;n=new Qr(JSON.stringify(t))}throw null==e||e(new Qr("An error occurred while requesting your Google Pay payment details.")),n}})}_interactWithPaymentSheet(){return ia(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e),n=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(e),i="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;t&&(yield this._paymentIntegrationService.updateBillingAddress(t)),n&&(yield this._paymentIntegrationService.updateShippingAddress(n)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodId(),e,i)})}_getMethodId(){return ii(this._methodId,()=>new ri(ti.PaymentNotInitialized))}}var oa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class aa{constructor(e,t,n,i){this._scriptLoader=e,this._gateway=t,this._requestSender=n,this._formPoster=i,this._baseRequest={apiVersion:2,apiVersionMinor:0}}initialize(e,t,n,i){return oa(this,void 0,void 0,function*(){this._paymentsClient=yield this._scriptLoader.getGooglePaymentsClient(e().config.testMode,t),yield this._gateway.initialize(e,n,i),this._buildButtonPayloads()})}initializeWidget(){return oa(this,void 0,void 0,function*(){yield this._buildWidgetPayloads(),yield this._determineReadinessToPay(),this._prefetchGooglePaymentData()})}getNonce(e){return this._gateway.getNonce(e)}extraPaymentData(){return oa(this,void 0,void 0,function*(){return this._gateway.extraPaymentData()})}addPaymentButton(e,t){const n=document.querySelector(`#${e}`);if(!n)return;const i=this._getPaymentsClient().createButton(Object.assign(Object.assign({},t),{allowedPaymentMethods:[this._getBaseCardPaymentMethod()]}));return n.appendChild(i)}showPaymentSheet(){return oa(this,void 0,void 0,function*(){const e=this._getPaymentDataRequest();return this._getPaymentsClient().loadPaymentData(e)})}setExternalCheckoutXhr(e,t){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t)})}setExternalCheckoutForm(e,t,n){return oa(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t,!0,n)})}mapToBillingAddressRequestBody(e){return this._gateway.mapToBillingAddressRequestBody(e)}mapToShippingAddressRequestBody(e){return this._gateway.mapToShippingAddressRequestBody(e)}processAdditionalAction(e,t){return"processAdditionalAction"in this._gateway?this._gateway.processAdditionalAction(e,t):Promise.reject(e)}signOut(e){return oa(this,void 0,void 0,function*(){yield this._requestSender.get(`/remote-checkout/${e}/signout`)})}getCallbackTriggers(){return this._gateway.getCallbackTriggers()}setShouldRequestShipping(e){return this._gateway.setShouldRequestShipping(e)}handleShippingAddressChange(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleShippingAddressChange(e)})}handleShippingOptionChange(e){return oa(this,void 0,void 0,function*(){yield this._gateway.handleShippingOptionChange(e)})}handleCoupons(e){return oa(this,void 0,void 0,function*(){return this._gateway.handleCoupons(e)})}getTotalPrice(){return this._gateway.getTotalPrice()}_setExternalCheckout(e,t,n=!1,i){return oa(this,void 0,void 0,function*(){const r="/checkout.php",o=Object.assign({action:"set_external_checkout",provider:e},yield this._gateway.mapToExternalCheckoutData(t));if(n)return new Promise(e=>{this._formPoster.postForm(i?`${i}/checkout`:r,Object.assign(Object.assign({},o),{card_information:JSON.stringify(o.card_information)}),e)});yield this._requestSender.post(r,{headers:Object.assign({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},yr),body:o})})}isWebViewWithRestrictions(){return this._gateway.isWebViewWithRestrictions()}setIsWebViewExperimentOn(e){return this._gateway.setIsWebViewExperimentOn(e)}_prefetchGooglePaymentData(){const e=this._getPaymentDataRequest();e.transactionInfo=this._gateway.getTransactionInfo(),this._getPaymentsClient().prefetchPaymentData(e)}_determineReadinessToPay(){return oa(this,void 0,void 0,function*(){try{const{result:e}=yield this._getPaymentsClient().isReadyToPay(this._getIsReadyToPayRequest());if(!1===e)throw new Qr("Google Pay is not supported by the current device and browser, please try another payment method.")}catch(e){if(e instanceof Qr)throw e;throw new Qr}})}_buildButtonPayloads(){this._baseCardPaymentMethod={type:"CARD",parameters:this._gateway.getCardParameters()}}_buildWidgetPayloads(){return oa(this,void 0,void 0,function*(){const e=this._getBaseCardPaymentMethod();this._cardPaymentMethod=Object.assign(Object.assign({},e),{tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:yield this._gateway.getPaymentGatewayParameters()}});const t=this._gateway.isWebViewWithRestrictions()?{shippingOptionRequired:!1}:{callbackIntents:this._gateway.getCallbackIntents(),offerInfo:this._gateway.getAppliedCoupons()};this._paymentDataRequest=Object.assign(Object.assign(Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[this._cardPaymentMethod],transactionInfo:this._gateway.getTransactionInfo(),merchantInfo:this._gateway.getMerchantInfo()}),yield this._gateway.getRequiredData()),t),this._isReadyToPayRequest=Object.assign(Object.assign({},this._baseRequest),{allowedPaymentMethods:[e]})})}_getBaseCardPaymentMethod(){return this._getOrThrow(this._baseCardPaymentMethod)}_getPaymentDataRequest(){return this._getOrThrow(this._paymentDataRequest)}_getIsReadyToPayRequest(){return this._getOrThrow(this._isReadyToPayRequest)}_getPaymentsClient(){return this._getOrThrow(this._paymentsClient)}_getOrThrow(e){return ii(e,()=>new ri(ti.PaymentNotInitialized))}}class sa{constructor(e){this._scriptLoader=e,this._window=window}getGooglePaymentsClient(e=!1,t){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript("https://pay.google.com/gp/p/js/pay.js"),!this._window.google)throw new mi;return void 0===this._paymentsClient&&(this._paymentsClient=new this._window.google.payments.api.PaymentsClient(Object.assign({environment:e?"TEST":"PRODUCTION"},null!=t?t:{}))),this._paymentsClient},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}function da(){return new sa(a())}const ca=fi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),la=fi(e=>{const t=n();return new ra(e,new aa(da(),new ea("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]);class ua extends ea{constructor(e){super("authorizenet",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return function(e){if(!function(e){return"paymentGatewayId"in e}(e))throw new ni(ei.MissingPaymentMethod)}(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.paymentGatewayId}}}const ha=fi(e=>new ra(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),pa=e=>"object"==typeof e&&null!==e&&"body"in e;function ma(e){if(!function(e){return"checkoutcomkey"in e}(e))throw new ni(ei.MissingPaymentMethod)}var ya=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ga extends ea{constructor(e,t){super("checkoutltd",e),this._requestSender=t}processAdditionalAction(e){return new Promise((t,n)=>{if(pa(e)&&function(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;return"string"==typeof(null===(t=n.three_ds_result)||void 0===t?void 0:t.acs_url)&&"string"==typeof n.three_ds_result.code}(e.body)&&"three_d_secure_required"===e.body.three_ds_result.code)return window.location.assign(e.body.three_ds_result.acs_url);n(e)})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ya(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new vi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"protocolVersion"in e&&"signature"in e&&"signedMessage"in e}(e))throw new ni(ei.MissingPaymentToken)}(i),n.nonce=yield this._tokenize(i),n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return ma(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.checkoutcomkey}}_tokenize(e){return ya(this,void 0,void 0,function*(){const t=this.getPaymentMethod().config.testMode?"https://api.sandbox.checkout.com/tokens":"https://api.checkout.com/tokens",n=this.getGooglePayInitializationData();ma(n);const{body:i}=yield this._requestSender.post(t,{credentials:!1,body:{type:"googlepay",token_data:e},headers:{Authorization:n.checkoutcomkey,"Content-Type":mr.Json,"X-XSRF-TOKEN":null}});return i.token})}}const fa=fi(e=>{const t=n();return new ra(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]);class va extends ea{constructor(e){super("cybersource",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const _a=fi(e=>new ra(e,new aa(da(),new va(e),n(),Ee())),[{id:"googlepaycybersourcev2"}]),Sa=fi(e=>new ra(e,new aa(da(),new va(e),n(),Ee())),[{id:"googlepaybnz"}]);class Ia extends ea{constructor(e){super("chase",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const wa=fi(e=>new ra(e,new aa(da(),new Ia(e),n(),Ee())),[{id:"googlepayorbital"}]);var Ca,ba,Pa,Oa,Ea,Aa,Ta,ka,Da,Ma,za,xa;!function(e){e.SHIPPING="shipping",e.BILLING="billing"}(Ca||(Ca={})),function(e){e.SPLIT="split",e.FULL="full",e.ORGANIZATION="organization"}(ba||(ba={})),function(e){e.Open="open",e.Expired="expired",e.Complete="complete"}(Pa||(Pa={})),function(e){e.Paid="paid",e.UnPaid="unpaid",e.NoPaymentRequired="no_payment_required"}(Oa||(Oa={})),function(e){e.SUCCESS="success",e.ERROR="error"}(Ea||(Ea={})),function(e){e.CreditCard="card",e.ACH="us_bank_account",e.Link="link",e.EPS="eps",e.GRABPAY="grabpay",e.BANCONTACT="bancontact",e.IDEAL="ideal",e.ALIPAY="alipay",e.KLARNA="klarna",e.OCS="optimized_checkout",e.CHECKOUT_SESSION="checkout_session"}(Aa||(Aa={})),function(e){e.NEVER="never",e.AUTO="auto",e.ALWAYS="always",e.PAYMENT="payment",e.IF_REQUIRED="if_required"}(Ta||(Ta={})),function(e){e.V3="v3",e.ACACIA="acacia",e.BASIL="basil",e.CLOVER="clover"}(ka||(ka={})),function(e){e.PAYMENT="payment",e.AUTHENTICATION="linkAuthentication",e.SHIPPING="address",e.EXPRESS_CHECKOUT="expressCheckout"}(Da||(Da={})),function(e){e.REQUIRES_PAYMENT_METHOD="requires_payment_method",e.REQUIRES_CONFIRMATION="requires_confirmation",e.REQUIRES_ACTION="requires_action",e.PROCESSING="processing",e.SUCCEEDED="succeeded",e.CANCELED="canceled"}(Ma||(Ma={})),function(e){e.CLICK="click",e.CHANGE="change",e.READY="ready",e.SHIPPING_ADDRESS_CHANGE="shippingaddresschange",e.SHIPPING_RATE_CHANGE="shippingratechange",e.CONFIRM="confirm",e.CANCEL="cancel",e.LOADER_START="loaderstart"}(za||(za={})),function(e){e.ON_SESSION="on_session",e.OFF_SESSION="off_session"}(xa||(xa={}));var Na=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ra{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}getStripeClient(e,t,n,i,r){return Na(this,void 0,void 0,function*(){if(this.stripeWindow.bcStripeClient)return this.stripeWindow.bcStripeClient;const o=yield this.load(n),{stripePublishableKey:a,stripeConnectedAccount:s}=e,d=o(a,Object.assign(Object.assign(Object.assign(Object.assign({},s?{stripeAccount:s}:{}),t?{locale:t}:{}),i?{betas:i}:{}),r?{apiVersion:r}:{}));return Object.assign(this.stripeWindow,{bcStripeClient:d}),d})}getElements(e,t){return Na(this,void 0,void 0,function*(){let n=this.stripeWindow.bcStripeElements;return n?yield this.updateStripeElements(t):(n=e.elements(t),Object.assign(this.stripeWindow,{bcStripeElements:n})),n})}updateStripeElements(e){return Na(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeElements;t&&(t.update(e),yield t.fetchUpdates())})}getStripeCheckout(e,t){return Na(this,void 0,void 0,function*(){let n=yield this.getStoredStripeCheckout(t);return n||(n=yield e.initCheckout(t),Object.assign(this.stripeWindow,{bcStripeCheckout:n})),n})}load(e){return Na(this,void 0,void 0,function*(){if(!this.stripeWindow.Stripe&&(yield this.scriptLoader.loadScript(this.getScriptUrl(e)),!this.stripeWindow.Stripe))throw new mi;return this.stripeWindow.Stripe})}getScriptUrl(e){return e&&e!==ka.V3?`https://js.stripe.com/${e}/stripe.js`:"https://js.stripe.com/v3/"}getStoredStripeCheckout(e){return Na(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeCheckout;if(t)try{const{actions:n,error:i}=yield t.loadActions();if(i||!n)return void this.logErrorToConsole(i);const r=yield n.getSession(),o=e.clientSecret.split("_secret_")[0];if(r.id===o)return t}catch(e){return void this.logErrorToConsole(e)}})}logErrorToConsole(e){e?console.error(e):console.error("No stripe checkout actions available on loadActions().")}}const Fa=["payment_element_beta_2","alipay_pm_beta_1","link_default_integration_beta_1","shipping_address_element_beta_1","address_element_beta_1"],La="2020-03-02;alipay_beta=v1;link_beta=v1";function ja(e){if(!function(e){return"stripeConnectedAccount"in e&&"stripePublishableKey"in e&&"stripeVersion"in e}(e))throw new ni(ei.MissingPaymentMethod)}var Ba=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ua extends ea{constructor(e,t){super("stripe",e),this.paymentIntegrationService=e,this.scriptLoader=t}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return Ba(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new vi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"id"in e}(e))throw new ni(ei.MissingPaymentToken)}(i),n.nonce=i.id,n})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();ja(e);const{stripeVersion:t,stripePublishableKey:n,stripeConnectedAccount:i}=e;return{gateway:this.getGatewayIdentifier(),"stripe:version":t,"stripe:publishableKey":`${n}/${i}`}}processAdditionalAction(e,t){var n;return Ba(this,void 0,void 0,function*(){if(!t)throw new co(["payment"]);if(!pa(e)||("object"!=typeof(i=e.body)||null===i||!("three_ds_result"in i)||!("errors"in i)))throw e;var i;if(fe(e.body.errors,{code:"three_d_secure_required"})){const i=this.getGooglePayInitializationData();ja(i),this.stripeUPEClient=yield this.loadStripeJs(i,t);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this.stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this.stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if(null==o?void 0:o.error){if(this._throwDisplayableStripeError(o.error),this._isCancellationError(o.error))throw new Wi;throw new Qr}if(!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;return this.paymentIntegrationService.submitPayment({methodId:t,paymentData:{nonce:(null===(n=null==o?void 0:o.paymentIntent)||void 0===n?void 0:n.id)||r}})}throw e})}loadStripeJs(e,t){return Ba(this,void 0,void 0,function*(){if(this.stripeUPEClient)return this.stripeUPEClient;const n=this.paymentIntegrationService.getState().getCartLocale();return"googlepaystripeocs"===t&&e.useNewStripeJsVersion?this.scriptLoader.getStripeClient(e,n,ka.CLOVER):this.scriptLoader.getStripeClient(e,n,ka.V3,Fa,La)})}_isCancellationError(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))}_throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}}const qa=fi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeocs"}]),Va=fi(e=>new ra(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripeupe"}]);class Ga extends ea{constructor(e){super("worldpay",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return n=this,i=void 0,o=function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const Ha=fi(e=>new ra(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]);var Wa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class $a extends ea{constructor(e,t){super("braintree",e),this._braintreeSdk=t,this._methodId=Qo.BRAINTREE,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Wa(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);let r=i.getPaymentMethod.call(this);if(r.clientToken||(r=(yield this._service.loadPaymentMethod(this._methodId)).getPaymentMethodOrThrow(this._methodId)),!r.clientToken||!r.initializationData)throw new ni(ei.MissingPaymentMethod);return this._braintreeSdk.initialize(r.clientToken),this._braintreeGooglePayment=yield this._braintreeSdk.getBraintreeGooglePayment(),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});var n;return Wa(this,void 0,void 0,function*(){const i=yield t.getNonce.call(this,e),{clientToken:r,initializationData:o}=t.getPaymentMethod.call(this);if(!r||!o||!(null===(n=o.card_information)||void 0===n?void 0:n.bin))throw new ni(ei.MissingPaymentMethod);const{isThreeDSecureEnabled:a,card_information:{bin:s,isNetworkTokenized:d}}=o;if(a&&!d){const e=yield this._braintreeSdk.getBraintreeThreeDS(),{orderAmount:t}=this._service.getState().getOrderOrThrow();return(yield this._braintreePresent3DSChallenge(e,t,i,s)).nonce}return i})}extraPaymentData(){return Wa(this,void 0,void 0,function*(){return{deviceSessionId:yield this._getBraintreeDeviceData()}})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return Wa(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);let i;try{i=JSON.parse(n.nonce)}catch(e){throw new vi("Unable to parse response from Google Pay.")}return function(e){if(!function(e){return"object"==typeof e&&null!==e&&"androidPayCards"in e}(e))throw new ni(ei.MissingPaymentToken)}(i),n.nonce=i.androidPayCards[0].nonce,n.card_information.bin=i.androidPayCards[0].details.bin,n.card_information.isNetworkTokenized=i.androidPayCards[0].details.isNetworkTokenized,n})}getCardParameters(){return super.getCardParameters()}getPaymentGatewayParameters(){const e=Object.create(null,{getMerchantInfo:{get:()=>super.getMerchantInfo},getTransactionInfo:{get:()=>super.getTransactionInfo},getRequiredData:{get:()=>super.getRequiredData}});return Wa(this,void 0,void 0,function*(){return this.getBraintreeGooglePayment().createPaymentDataRequest(Object.assign({merchantInfo:e.getMerchantInfo.call(this),transactionInfo:e.getTransactionInfo.call(this),cardRequirements:{billingAddressRequired:!0,billingAddressFormat:"FULL"}},yield e.getRequiredData.call(this))).paymentMethodTokenizationParameters.parameters})}getBraintreeGooglePayment(){if(!this._braintreeGooglePayment)throw new ni(ei.MissingPaymentMethod);return this._braintreeGooglePayment}_getBraintreeDeviceData(){return Wa(this,void 0,void 0,function*(){const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e})}_braintreePresent3DSChallenge(e,t,n,i){return new An(e.verifyCard({amount:t,bin:i,nonce:n,onLookupComplete:(e,t)=>{t()}})).promise}}const Ya=fi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new ra(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),Ka={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},Ja=["ar_BH","ar_DZ","ar_EG","ar_JO","ar_KW","ar_MA","ar_OM","ar_QA","ar_SA","ar_TN","ar_YE","ar_AE","bg_BG","cs_CZ","da_DK","da_FO","da_GL","de_AT","de_CH","de_DE","de_LU","el_GR","en_AD","en_AE","en_AG","en_AI","en_AL","en_AM","en_AN","en_AO","en_AT","en_AU","en_AW","en_AZ","en_BB","en_BE","en_BH","en_BJ","en_BM","en_BN","en_BS","en_BT","en_BW","en_BY","en_BZ","en_C2","en_CA","en_CD","en_CG","en_CH","en_CI","en_CK","en_CL","en_CM","en_CN","en_CO","en_CR","en_CV","en_CY","en_CZ","en_DE","en_DJ","en_DK","en_DM","en_DO","en_DZ","en_EC","en_EE","en_EG","en_ER","en_ES","en_ET","en_FI","en_FJ","en_FK","en_FM","en_FO","en_FR","en_GA","en_GB","en_GD","en_GE","en_GF","en_GI","en_GL","en_GM","en_GN","en_GP","en_GR","en_GT","en_GW","en_GY","en_HK","en_HN","en_HR","en_HU","en_ID","en_IE","en_IL","en_IN","en_IS","en_IT","en_JM","en_JO","en_JP","en_KE","en_KG","en_KH","en_KI","en_KM","en_KN","en_KR","en_KW","en_KY","en_KZ","en_LA","en_LC","en_LI","en_LK","en_LS","en_LT","en_LU","en_LV","en_MA","en_MC","en_MD","en_ME","en_MG","en_MH","en_MK","en_ML","en_MN","en_MQ","en_MR","en_MS","en_MT","en_MU","en_MV","en_MW","en_MY","en_MZ","en_NA","en_NC","en_NE","en_NF","en_NG","en_NI","en_NL","en_NO","en_NP","en_NR","en_NU","en_NZ","en_OM","en_PA","en_PE","en_PF","en_PG","en_PH","en_PL","en_PM","en_PN","en_PT","en_PW","en_PY","en_QA","en_RE","en_RO","en_RS","en_RU","en_RW","en_SA","en_SB","en_SC","en_SE","en_SG","en_SH","en_SI","en_SJ","en_SK","en_SL","en_SM","en_SN","en_SO","en_SR","en_ST","en_SV","en_SZ","en_TC","en_TD","en_TG","en_TH","en_TJ","en_TM","en_TN","en_TO","en_TR","en_TT","en_TV","en_TW","en_TZ","en_UA","en_UG","en_US","en_UY","en_VA","en_VC","en_VE","en_VG","en_VN","en_VU","en_WF","en_WS","en_YE","en_YT","en_ZA","en_ZM","en_ZW","es_AD","es_AI","es_AO","es_AR","es_AW","es_BB","es_BJ","es_BM","es_BO","es_BS","es_BZ","es_CD","es_CG","es_CK","es_CL","es_CO","es_CR","es_CV","es_DJ","es_DM","es_DO","es_DZ","es_EC","es_EG","es_ER","es_ES","es_ET","es_FJ","es_FK","es_FO","es_GA","es_GD","es_GE","es_GI","es_GL","es_GM","es_GN","es_GT","es_GW","es_GY","es_HN","es_IE","es_JM","es_JO","es_KE","es_KG","es_KI","es_KM","es_KN","es_KW","es_KY","es_KZ","es_LC","es_LI","es_LS","es_LU","es_MA","es_MG","es_MH","es_ML","es_MR","es_MS","es_MU","es_MW","es_MX","es_MZ","es_NA","es_NC","es_NE","es_NF","es_NI","es_NR","es_NU","es_NZ","es_OM","es_PA","es_PE","es_PF","es_PG","es_PM","es_PN","es_PW","es_PY","es_QA","es_RS","es_RW","es_SA","es_SB","es_SC","es_SH","es_SJ","es_SL","es_SM","es_SN","es_SO","es_SR","es_ST","es_SV","es_SZ","es_TC","es_TD","es_TG","es_TJ","es_TM","es_TN","es_TT","es_TV","es_UA","es_UG","es_US","es_UY","es_VA","es_VC","es_VE","es_VG","es_VU","es_WF","es_YE","es_ZM","et_EE","fi_FI","fr_AD","fr_AE","fr_AI","fr_AM","fr_AO","fr_AW","fr_AZ","fr_BB","fr_BE","fr_BF","fr_BI","fr_BJ","fr_BM","fr_BS","fr_BZ","fr_CA","fr_CD","fr_CG","fr_CH","fr_CI","fr_CK","fr_CM","fr_CV","fr_DJ","fr_DM","fr_DO","fr_DZ","fr_EC","fr_ER","fr_ET","fr_FJ","fr_FK","fr_FO","fr_FR","fr_GA","fr_GD","fr_GE","fr_GF","fr_GI","fr_GL","fr_GM","fr_GN","fr_GP","fr_GT","fr_GW","fr_GY","fr_HN","fr_IE","fr_JM","fr_JO","fr_KE","fr_KG","fr_KI","fr_KM","fr_KN","fr_KW","fr_KY","fr_KZ","fr_LC","fr_LI","fr_LS","fr_LU","fr_MA","fr_MC","fr_MG","fr_MH","fr_ML","fr_MQ","fr_MR","fr_MS","fr_MU","fr_MW","fr_MZ","fr_NA","fr_NC","fr_NE","fr_NF","fr_NI","fr_NR","fr_NU","fr_NZ","fr_OM","fr_PA","fr_PE","fr_PF","fr_PG","fr_PM","fr_PN","fr_PW","fr_QA","fr_RE","fr_RS","fr_RW","fr_SA","fr_SB","fr_SC","fr_SH","fr_SJ","fr_SL","fr_SM","fr_SN","fr_SO","fr_SR","fr_ST","fr_SV","fr_SZ","fr_TC","fr_TD","fr_TG","fr_TJ","fr_TM","fr_TN","fr_TT","fr_TV","fr_UA","fr_UG","fr_US","fr_UY","fr_VA","fr_VC","fr_VE","fr_VG","fr_VU","fr_WF","fr_YE","fr_YT","fr_ZA","fr_ZM","he_IL","hu_HU","id_ID","it_IT","ja_JP","ko_KR","lv_LV","lt_LT","ms_BN","ms_MY","nl_BE","nl_NL","pl_PL","pt_BR","pt_PT","ro_RO","ru_EE","ru_LT","ru_LV","ru_RU","ru_UA","si_LK","sk_SK","sl_SI","sq_AL","sv_SE","tl_PH","th_TH","tr_TR","vi_VN","zh_C2","zh_CN","zh_HK","zh_TW","zh_AD","zh_AE","zh_AI","zh_AO","zh_AW","zh_BB","zh_BH","zh_BJ","zh_BM","zh_BS","zh_BZ","zh_CD","zh_CG","zh_CK","zh_CL","zh_CO","zh_CV","zh_DJ","zh_DM","zh_DO","zh_DZ","zh_EC","zh_EG","zh_ER","zh_ET","zh_FJ","zh_FK","zh_FO","zh_GA","zh_GD","zh_GE","zh_GI","zh_GL","zh_GM","zh_GN","zh_GT","zh_GW","zh_GY","zh_HN","zh_IE","zh_JM","zh_JO","zh_KE","zh_KG","zh_KI","zh_KM","zh_KN","zh_KW","zh_KY","zh_KZ","zh_LC","zh_LI","zh_LS","zh_LT","zh_LU","zh_MA","zh_MG","zh_MH","zh_ML","zh_MR","zh_MS","zh_MU","zh_MW","zh_MZ","zh_NA","zh_NC","zh_NE","zh_NF","zh_NI","zh_NR","zh_NU","zh_NZ","zh_OM","zh_PA","zh_PE","zh_PF","zh_PG","zh_PM","zh_PN","zh_PW","zh_QA","zh_RS","zh_RW","zh_SA","zh_SB","zh_SC","zh_SH","zh_SJ","zh_SL","zh_SM","zh_SN","zh_SO","zh_SR","zh_ST","zh_SV","zh_SZ","zh_TC","zh_TD","zh_TG","zh_TJ","zh_TM","zh_TN","zh_TT","zh_TV","zh_UA","zh_UG","zh_US","zh_UY","zh_VA","zh_VC","zh_VE","zh_VG","zh_VU","zh_WF","zh_YE","zh_ZA","zh_ZM"];function Za(e){if(!e)return;let t;if(e.includes("-")){const[n,i]=e.split("-");t=`${n}_${i.toUpperCase()}`}else t=`${e}_${e.toUpperCase()}`;return Ja.includes(t)?t:void 0}var Qa=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xa{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,n,i){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return Qa(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Qa(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t,intent:a},l&&{locale:l}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ni(ei.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function es(e){if(!function(e){return!!e.initializationData&&"attributionId"in e.initializationData&&"isVenmoEnabled"in e.initializationData&&"isGooglePayEnabled"in e.initializationData&&"isPayPalCreditAvailable"in e.initializationData}(e))throw new ni(ei.MissingPaymentMethod)}var ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ns extends ea{constructor(e,t){super("paypalsb",e),this.payPalCommerceSdk=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return ts(this,void 0,void 0,function*(){const c=this.service.getState(),l=null!==(o=null===(r=c.getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!l)throw new ni(ei.MissingPaymentMethod);yield i.initialize.call(this,e,t,l);const u=i.getPaymentMethod.call(this);if(!u.initializationData)throw new ni(ei.MissingPaymentMethod);es(u);const h=yield this.payPalCommerceSdk.getPayPalGooglePaySdk(u,l,c.getLocale());this.googlepayConfig=yield h.Googlepay().config();const{allowedPaymentMethods:p}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=p[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ts(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const is=fi(e=>new ra(e,new aa(da(),new ns(e,new Xa(a())),n(),Ee())),[{id:"googlepaypaypalcommerce"}]);var rs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class os extends ea{constructor(e,t){super("googlepay_bigcommerce_payments",e),this.payPalSdkHelper=t,this.service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return rs(this,void 0,void 0,function*(){const c=null!==(o=null===(r=this.service.getState().getStoreConfig())||void 0===r?void 0:r.currency.code)&&void 0!==o?o:n;if(!c)throw new ni(ei.MissingPaymentMethod);yield i.initialize.call(this,e,t,c);const l=i.getPaymentMethod.call(this);if(!l.initializationData)throw new ni(ei.MissingPaymentMethod);es(l);const u=yield this.payPalSdkHelper.getPayPalGooglePaySdk(l,c);this.googlepayConfig=yield u.Googlepay().config();const{allowedPaymentMethods:h}=this.googlepayConfig;this.setGatewayIdentifier(null===(d=null===(s=null===(a=h[0])||void 0===a?void 0:a.tokenizationSpecification)||void 0===s?void 0:s.parameters)||void 0===d?void 0:d.gateway)})}getPaymentGatewayParameters(){if(this.googlepayConfig){const{allowedPaymentMethods:e}=this.googlepayConfig,{gatewayMerchantId:t}=e[0].tokenizationSpecification.parameters;return{gateway:this.getGatewayIdentifier(),gatewayMerchantId:t}}return{gateway:this.getGatewayIdentifier()}}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return rs(this,void 0,void 0,function*(){const n=yield t.mapToExternalCheckoutData.call(this,e);return n.nonce=btoa(n.nonce),n})}}const as=fi(e=>new ra(e,new aa(da(),new os(e,new Nr(a())),n(),Ee())),[{id:"googlepay_bigcommerce_payments"}]);function ss(){const{navigator:e}=window;let t;return t=e.language?e.language:e.userLanguage,{color_depth:window.screen.colorDepth||24,java_enabled:"function"==typeof e.javaEnabled&&e.javaEnabled(),language:t,screen_height:window.screen.height,screen_width:window.screen.width,time_zone_offset:(new Date).getTimezoneOffset().toString()}}var ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cs extends ea{constructor(e,t){super("worldlinena",e),this.formPoster=t}extraPaymentData(){return ds(this,void 0,void 0,function*(){return Promise.resolve({browser_info:ss()})})}processAdditionalAction(e){return ds(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&fe(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}}const ls=fi(e=>new ra(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);var us,hs,ps,ms,ys,gs,fs,vs,_s,Ss,Is=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ws{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return Is(this,void 0,void 0,function*(){if(!this.window.paypal||r){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypal)throw new mi}return this.window.paypal})}getPayPalFastlaneSdk(e,t,n,i){return Is(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const r=this.getPayPalFastlaneSdkConfiguration(e,t,n,i);if(yield this.loadPayPalSdk(r),!this.window.paypalFastlaneSdk)throw new mi}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,n,i,r){return Is(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||r){const r=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i);yield this.loadPayPalSdk(r)}if(!this.window.paypalGooglePay)throw new mi;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t,n){return Is(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t,n);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new mi}return this.window.paypalApms})}getPayPalMessages(e,t,n){return Is(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t,n);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new mi;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Is(this,void 0,void 0,function*(){const n=this.transformConfig(e),i=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(n).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:i})})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!a||!a.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:f=[],isGooglePayEnabled:v}=a,_=p||i,S="paypalcommercecreditcards"===r||"bigcommerce_payments_creditcards"===r,I=S?["card"]:[],w=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=v?["googlepay"]:[],P=i?["card-fields"]:[],O=[...S?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!f.includes(e))],E=[...I,...w,...C,...f],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:_,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}getPayPalFastlaneSdkConfiguration(e,t,n,i){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,attributionId:c}=o,l=Za(i);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t},l&&{locale:l}),{intent:a}),attributes:{"data-client-metadata-id":n.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":c,"data-sdk-client-token":r}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,n,i=!0){const{clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:a,clientId:s,merchantId:d,buyerCountry:c,attributionId:l,isHostedCheckoutEnabled:u,isDeveloperModeApplicable:h}=o,p=u||i,m=Za(n);return{options:Object.assign(Object.assign({"client-id":s,"merchant-id":d,commit:p,components:["googlepay"],currency:t,intent:a},h&&{"buyer-country":c}),m&&{locale:m}),attributes:{"data-partner-attribution-id":l,"data-client-token":r,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ni(ei.MissingPaymentMethod);const{intent:r,clientId:o,merchantId:a,buyerCountry:s,attributionId:d,isDeveloperModeApplicable:c,availableAlternativePaymentMethods:l=[],enabledAlternativePaymentMethods:u=[]}=i,h=u,p=l.filter(e=>!u.includes(e)),m=Za(n);return{options:Object.assign(Object.assign({"client-id":o,"merchant-id":a,"enable-funding":h.length>0?h:void 0,"disable-funding":p.length>0?p:void 0,commit:!0,components:["buttons","payment-fields"],currency:t,intent:r},c&&{"buyer-country":s}),m&&{locale:m}),attributes:{"data-partner-attribution-id":d,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t,n){const{initializationData:i}=e;if(!i||!i.clientId)throw new ni(ei.MissingPaymentMethod);const{clientId:r,merchantId:o,attributionId:a,isDeveloperModeApplicable:s,buyerCountry:d}=i,c=Za(n);return{options:Object.assign(Object.assign({"client-id":r,"merchant-id":o,components:["messages"],currency:t},s&&{"buyer-country":d}),c&&{locale:c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":a}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}function Cs(){return new ws(o())}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(us||(us={})),(hs||(hs={})).Always="SCA_ALWAYS",function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(ps||(ps={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(ms||(ms={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(ys||(ys={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(gs||(gs={})),function(e){e.pill="pill",e.rect="rect"}(fs||(fs={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(vs||(vs={})),(_s||(_s={})).OXXO="oxxo",function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(Ss||(Ss={}));var bs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ps{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalRequestSender=n,this.paypalSdkLoader=i}loadPayPalSdk(e,t,n,i){return bs(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e),s=r.getLocale();return this.paypalSdk=yield this.paypalSdkLoader.getPayPalSDK(a,o,s,n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return bs(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ni(ei.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return bs(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(e,t,n){return bs(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getConsignmentsOrThrow()[0];try{yield this.paypalRequestSender.updateOrder(e,Object.assign(Object.assign({availableShippingOptions:o.availableShippingOptions,cartId:r.id,selectedShippingOption:o.selectedShippingOption},t?{methodId:t}:{}),n?{orderId:n}:{}))}catch(e){throw new nr}})}getOrderStatus(e,t){return bs(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ni(ei.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===Rt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return bs(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{if(t.selectedShippingOption){const n=t.selectedShippingOption.id;return e.id===n}return!1}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e={}){const{color:t,height:n,label:i,shape:r}=e,o={color:t&&gs[t]?t:void 0,height:this.getValidHeight(n),label:i&&ys[i]?i:void 0,shape:r&&fs[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Os=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Es{constructor(e){this.requestSender=e}createOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put(n,{headers:r,body:i})).body})}getOrderStatus(e,t){return Os(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}const As=e=>{const{getHost:t}=e.getState();return new Ps(Ee(),e,new Es(n({host:t()})),Cs())};var Ts=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const ks=class{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}createPayPalButton(e,t,n,i){const{style:r,fundingSource:o,isAppSwitchEnabled:a,isHostedCheckoutEnabled:s,onClick:d,onCancel:c,onPaymentComplete:l,onError:u}=n;this.onError=u;const h=this.paypalIntegrationService.getPayPalSdkOrThrow();if(!Object.values(h.FUNDING).includes(o))throw new vi('Unable to initialize PayPal button because "fundingSource" argument is not valid funding source.');const p=Object.assign(Object.assign({},!a&&{onShippingAddressChange:t=>this.onShippingAddressChange(t,e),onShippingOptionsChange:t=>this.onShippingOptionsChange(t,e)}),{onApprove:(n,i)=>this.onHostedCheckoutApprove(n,i,t,e,l)});return h.Buttons(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({fundingSource:o,style:this.paypalIntegrationService.getValidButtonStyle(r)},a&&{appSwitchWhenAvailable:!0}),{createOrder:()=>Ts(this,void 0,void 0,function*(){if(i){const e=yield this.paypalIntegrationService.createBuyNowCartOrThrow(i);yield this.paymentIntegrationService.loadCheckout(e.id)}return this.paypalIntegrationService.createOrder(e)}),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)}),d?{onClick:d}:{}),c?{onCancel:c}:{}),s&&p))}onHostedCheckoutApprove(e,t,n,i,r){return Ts(this,void 0,void 0,function*(){if(!e.orderID)throw new ni(ei.MissingOrderId);const o=this.paymentIntegrationService.getState().getCartOrThrow(),a=yield t.order.get();try{const t=this.paypalIntegrationService.getBillingAddressFromOrderDetails(a);if(yield this.paymentIntegrationService.updateBillingAddress(t),o.lineItems.physicalItems.length>0){const e=this.paypalIntegrationService.getShippingAddressFromOrderDetails(a);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalIntegrationService.updateOrder(i)}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalIntegrationService.submitPayment(n,e.orderID),r&&"function"==typeof r&&r()}catch(e){this.handleError(e)}})}onShippingAddressChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(n),yield this.paymentIntegrationService.updateShippingAddress(n);const e=this.paypalIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}onShippingOptionsChange(e,t){return Ts(this,void 0,void 0,function*(){const n=this.paypalIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(n.id),yield this.paypalIntegrationService.updateOrder(t)}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}};var Ds=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ms{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalButtonCreationService=n}initialize(e){return Ds(this,void 0,void 0,function*(){const{paypalcommerce:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.paypalcommerce.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.paypalcommerce.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ds(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Ds(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()}renderButton(e,t){var n,i;const{container:r,onClick:o,onComplete:a,onError:s}=t,d=this.paypalIntegrationService.getPayPalSdkOrThrow(),c=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:l,paymentButtonStyles:u,isAppSwitchEnabled:h}=c.initializationData||{},{checkoutTopButtonStyles:p}=u||{},m=Object.assign(Object.assign(Object.assign({fundingSource:d.FUNDING.PAYPAL,isAppSwitchEnabled:h,isHostedCheckoutEnabled:l,style:Object.assign(Object.assign({},p),{height:Ir})},o&&{onClick:()=>o()}),l&&a&&{onPaymentComplete:()=>a()}),{onError:s}),y=this.paypalButtonCreationService.createPayPalButton("paypalcommerce",e,m);y.isEligible()?(null===(n=y.hasReturned)||void 0===n?void 0:n.call(y))&&h?null===(i=y.resume)||void 0===i||i.call(y):y.render(`#${r}`):this.paypalIntegrationService.removeElement(r)}}const zs=fi(e=>{const t=As(e),n=new ks(e,t);return new Ms(e,t,n)},[{id:"paypalcommerce"}]);var xs,Ns,Rs,Fs,Ls,js,Bs;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(xs||(xs={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Ns||(Ns={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Rs||(Rs={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(Fs||(Fs={})),function(e){e.pill="pill",e.rect="rect"}(Ls||(Ls={})),function(e){e.OXXO="oxxo",e.IDEAL="ideal"}(js||(js={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(Bs||(Bs={}));var Us=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qs{constructor(e,t,n,i){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=i}loadPayPalSdk(e,t,n,i){return Us(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e);return this.paypalSdk=yield this.paypalCommerceScriptLoader.getPayPalSDK(a,o,r.getLocale(),n,i),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new mi;return this.paypalSdk}createBuyNowCartOrThrow(e){return Us(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new ni(ei.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new er}})}createOrder(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return i})}createOrderCardFields(e,t){return Us(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:i,setupToken:r}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:n},t));return Object.assign({orderId:i},r?{setupToken:r}:{})})}updateOrder(){return Us(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0];try{yield this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new nr}})}getOrderStatus(e,t){return Us(this,void 0,void 0,function*(){try{const{status:n}=yield this.paypalCommerceRequestSender.getOrderStatus(e,t);return n}catch(e){throw new nr}})}tokenizePayment(e,t){const n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new ni(ei.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===Rt.BuyNow&&{cart_id:n.id}))}submitPayment(e,t,n){return Us(this,void 0,void 0,function*(){const i={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}};yield this.paymentIntegrationService.submitPayment(Object.assign({methodId:e,paymentData:i},n?{gatewayId:n}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],i=n.find(e=>e.isRecommended),r=(e?n.find(t=>t.id===e):n.find(e=>{var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)}))||i||n[0];if(!r)throw new Error("Your order can't be shipped to this address");return r}getAddress(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:(null==e?void 0:e.phone)||"",company:"",address1:(null==e?void 0:e.address1)||"",address2:(null==e?void 0:e.address2)||"",city:(null==e?void 0:e.city)||"",countryCode:(null==e?void 0:e.countryCode)||"",postalCode:(null==e?void 0:e.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==e?void 0:e.stateOrProvinceCode)||"",customFields:[]}}getBillingAddressFromOrderDetails({payer:e}){var t,n;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,address2:e.address.address_line_2,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1,phone:null===(n=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===n?void 0:n.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:n}=e,{address:i,name:{full_name:r}}=n[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:i.address_line_1,address2:i.address_line_2,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})}getValidButtonStyle(e){const{color:t,height:n,label:i,shape:r}=e||{},o={color:t&&Fs[t]?t:void 0,height:this.getValidHeight(n),label:i&&Rs[i]?i:void 0,shape:r&&Ls[r]?r:void 0};return ue(o,J)}getValidHeight(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40}removeElement(e){const t=e&&document.getElementById(e);t&&(t.style.display="none")}}var Vs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Gs{constructor(e){this.requestSender=e}createOrder(e,t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/payment/${e}`,i=t,r=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.post(n,{headers:r,body:i})).body})}updateOrder(e){return Vs(this,void 0,void 0,function*(){const t=e,n=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:t})).body})}getOrderStatus(e="paypalcommerce",t){return Vs(this,void 0,void 0,function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},t))).body})}}var Hs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ws{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,n,i,r){return Hs(this,void 0,void 0,function*(){const o=this.getPayPalSdkScriptConfigOrThrow(e,t,n,i);return this.loadPayPalSDK(o,r)})}loadPayPalSDK(e,t=!1){return Hs(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),n=this.transformConfig(e.attributes),i=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(i,{async:!0,attributes:n})}if(!this.window.paypal)throw new mi;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,n,i=!0){const{id:r,clientToken:o,initializationData:a}=e;if(!(null==a?void 0:a.clientId))throw new ni(ei.MissingPaymentMethod);const{intent:s,clientId:d,merchantId:c,buyerCountry:l,attributionId:u,isVenmoEnabled:h,isHostedCheckoutEnabled:p,isPayPalCreditAvailable:m,isDeveloperModeApplicable:y,availableAlternativePaymentMethods:g=[],enabledAlternativePaymentMethods:f=[],isGooglePayEnabled:v}=a,_=p||i,S="paypalcommercecreditcards"===r,I=S?["card"]:[],w=m?["credit","paylater"]:[],C=h?["venmo"]:[],b=v?["googlepay"]:[],P=i?["card-fields"]:[],O=[...S?[]:["card"],...m?[]:["credit","paylater"],...h?[]:["venmo"],...g.filter(e=>!f.includes(e))],E=[...I,...w,...C,...f],A=Za(n);return{options:Object.assign(Object.assign({"client-id":d,"merchant-id":c,"enable-funding":E.length>0?E:void 0,"disable-funding":O.length>0?O:void 0,commit:_,components:["buttons","hosted-fields","payment-fields","legal",...b,...P],currency:t,intent:s},y&&{"buyer-country":l}),A&&{locale:A}),attributes:{"data-partner-attribution-id":u,"data-client-token":o}}}transformConfig(e){let t={};return Object.keys(e).forEach(n=>{const i=e[n];null==i||""===i||Array.isArray(i)&&0===i.length||(t=Object.assign(Object.assign({},t),{[n]:Array.isArray(i)?i.join(","):i}))}),t}}const $s=e=>{const{getHost:t}=e.getState();return new qs(Ee(),e,new Gs(n({host:t()})),new Ws(a()))};var Ys=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ks{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=ce}initialize(e){return Ys(this,void 0,void 0,function*(){const{paypalcommercecredit:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.paypalcommercecredit.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.paypalcommercecredit.onClick" argument is not a function.');this.onError=t.onError||ce,this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Ys(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Ys(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()}renderButton(e,t){const{container:n,onComplete:i,onClick:r}=t,o=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:s,paymentButtonStyles:d,isAppSwitchEnabled:c}=a.initializationData||{},{checkoutTopButtonStyles:l}=d||{},u=Object.assign({createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},r&&{onClick:()=>r()}),h=Object.assign(Object.assign({},!c&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,n)=>this.onHostedCheckoutApprove(t,n,e,i)}),p=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT];let m=!1;p.forEach(e=>{if(!m){const t=Object.assign(Object.assign({fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},l),{height:Ir}))},u),s&&h),i=o.Buttons(t);i.isEligible()&&(i.render(`#${n}`),m=!0)}}),m||this.paypalCommerceIntegrationService.removeElement(n)}onHostedCheckoutApprove(e,t,n,i){return Ys(this,void 0,void 0,function*(){if(!e.orderID)throw new ni(ei.MissingOrderId);const r=this.paymentIntegrationService.getState().getCartOrThrow(),o=yield t.order.get();try{const t=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(o);if(yield this.paymentIntegrationService.updateBillingAddress(t),r.lineItems.physicalItems.length>0){const e=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(o);yield this.paymentIntegrationService.updateShippingAddress(e),yield this.paypalCommerceIntegrationService.updateOrder()}yield this.paymentIntegrationService.submitOrder({},{params:{methodId:n}}),yield this.paypalCommerceIntegrationService.submitPayment(n,e.orderID),i&&"function"==typeof i&&i()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.countryCode,postalCode:e.shippingAddress.postalCode,stateOrProvinceCode:e.shippingAddress.state});try{yield this.paymentIntegrationService.updateBillingAddress(t),yield this.paymentIntegrationService.updateShippingAddress(t);const e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow();yield this.paymentIntegrationService.selectShippingOption(e.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}onShippingOptionsChange(e){return Ys(this,void 0,void 0,function*(){const t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id);try{yield this.paymentIntegrationService.selectShippingOption(t.id),yield this.paypalCommerceIntegrationService.updateOrder()}catch(e){this.handleError(e)}})}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const Js=fi(e=>new Ks(e,$s(e)),[{id:"paypalcommercecredit"}]);var Zs=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Qs{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return Zs(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,methodId:n}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(!t.container)throw new vi('Unable to initialize payment because "options.paypalcommercevenmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new vi('Unable to initialize payment because "options.paypalcommercevenmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(n)||(yield this.paymentIntegrationService.loadPaymentMethod(n));const i=yield this.paypalCommerceIntegrationService.loadPayPalSdk(n);i&&i.Buttons&&"function"==typeof i.Buttons?this.renderButton(n,t):console.error("[BC PayPal]: PayPal Button could not be rendered, due to issues with loading PayPal SDK")})}deinitialize(){return Promise.resolve()}signIn(e,t){return Zs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Zs(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()}renderButton(e,t){const{container:n,onClick:i}=t,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:a}=o.initializationData||{},{checkoutTopButtonStyles:s}=a||{},d=Object.assign({fundingSource:r.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},s),{height:Ir})),createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},i&&{onClick:()=>i()}),c=r.Buttons(d);c.isEligible()?c.render(`#${n}`):this.paypalCommerceIntegrationService.removeElement(n)}}const Xs=fi(e=>new Qs(e,$s(e)),[{id:"paypalcommercevenmo"}]);var ed=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class td{constructor(){this.window=window}initializePayPalFastlane(e,t,n){return ed(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("fastlaneEnv","sandbox"),window.localStorage.setItem("axoEnv","sandbox")),!this.window.paypalFastlane){const t={root:{backgroundColorPrimary:"transparent"}};this.window.paypalFastlane=yield e.Fastlane({styles:n||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new mi;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return ed(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return ed(this,void 0,void 0,function*(){return e?this.getPayPalFastlaneOrThrow().identity.triggerAuthenticationFlow(e):{}})}updateStorageSessionId(e){const t=new Date;t.setDate(t.getDate()+14);const n={expires:t,secure:!0};Fr.set("bc-fastlane-sessionId",e,n)}removeStorageSessionId(){Fr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Fr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var n,i,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(i=null===(n=null==a?void 0:a.card)||void 0===n?void 0:n.paymentSource)||void 0===i?void 0:i.card)||void 0===r?void 0:r.billingAddress,d=null==a?void 0:a.shippingAddress,c=null==a?void 0:a.name,l=null==a?void 0:a.card,u=d?this.mapPayPalToBcAddress(d.address,d.name,d.phoneNumber):void 0,h=s&&c?this.mapPayPalToBcAddress(s,c,null==d?void 0:d.phoneNumber):void 0,p=l?this.mapPayPalToBcInstrument(e,l):[],m=this.filterAddresses([u,h]);return{authenticationState:o||vs.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return[{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Pr.PAN,type:"card"}]}mapBcToPayPalAddress(e){return{company:(null==e?void 0:e.company)||"",addressLine1:(null==e?void 0:e.address1)||"",addressLine2:(null==e?void 0:e.address2)||"",adminArea1:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",adminArea2:(null==e?void 0:e.city)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCode:(null==e?void 0:e.countryCode)||""}}mapPayPalToBcAddress(e,t,n,i){const[r,o]=t.fullName.split(" "),a=(null==n?void 0:n.nationalNumber)||"",s=(null==n?void 0:n.countryCode)||"";return{id:Date.now(),type:"paypal-address",firstName:t.firstName||r||"",lastName:t.lastName||o||"",company:e.company||"",address1:e.addressLine1,address2:e.addressLine2||"",city:e.adminArea2,stateOrProvince:e.adminArea1,stateOrProvinceCode:e.adminArea1,country:e.countryCode||"",countryCode:e.countryCode||"",postalCode:e.postalCode,phone:s+a,customFields:i||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return Y(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return le(e,["id","phone"])}}function nd(){return new td}function id(e){return"string"!=typeof e}function rd(e,t){if(t||e)return function(e){var t,n;const i={},r=ue(e.root,id),o=ue(e.input,id),a=ue(e.toggle,id),s=ue(null===(t=e.text)||void 0===t?void 0:t.body,id),d=ue(null===(n=e.text)||void 0===n?void 0:n.caption,id),c=e.branding;return Object.keys(r).length&&(i.root=r),Object.keys(o).length&&(i.input=o),Object.keys(a).length&&(i.toggle=a),Object.keys(s).length&&(i.text={},i.text.body=s),Object.keys(d).length&&(i.text=Object.assign({},i.text),i.text.caption=d),c&&(i.branding=c),i}(function(e,t){var n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,f,v,_,S,I,w,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.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===(c=null==t?void 0:t.input)||void 0===c?void 0:c.borderColor),focusBorderColor:(null==e?void 0:e.fastlaneInputSettingsFocusBorderBase)||(null===(l=null==t?void 0:t.input)||void 0===l?void 0:l.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===(p=null==t?void 0:t.input)||void 0===p?void 0:p.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===(y=null==t?void 0:t.toggle)||void 0===y?void 0:y.colorSecondary)},text:{body:{color:(null==e?void 0:e.fastlaneTextBodySettingsColor)||(null===(f=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===f?void 0:f.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(_=null===(v=null==t?void 0:t.text)||void 0===v?void 0:v.body)||void 0===_?void 0:_.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(S=null==t?void 0:t.text)||void 0===S?void 0:S.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var od=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ad{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalSdkScriptLoader=t,this.paypalFastlaneUtils=n}initialize(e){var t;return od(this,void 0,void 0,function*(){const{methodId:n,paypalcommercefastlane:i}=e;if(!n)throw new vi('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(n);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(n),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(o,r.currency.code,r.id,e.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(n,i))}catch(e){}return Promise.resolve()})}deinitialize(){return od(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:void 0,addresses:void 0,instruments:void 0}),this.paypalFastlaneUtils.removeStorageSessionId()})}signOut(e){return od(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return od(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:n,methodId:i}=e||{};if(!i)throw new vi('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof n)throw new vi('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(this.paymentIntegrationService.getState().getCustomerOrThrow().isGuest){t&&"function"==typeof t&&t();try{yield this.runPayPalAuthenticationFlowOrThrow(i)}catch(e){}}n()})}runPayPalAuthenticationFlowOrThrow(e){return od(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow().id,i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.paypalFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===vs.CANCELED;yield this.updateCustomerDataState(e,s),d?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(n)})}updateCustomerDataState(e,t){var n;return od(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow(),{authenticationState:r,addresses:o,billingAddress:a,shippingAddress:s,instruments:d}=this.paypalFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,t);if(yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:r,addresses:o,instruments:d}),a&&(yield this.paymentIntegrationService.updateBillingAddress(a)),s&&i.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),i=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=i.initializationData||{},o=t.getConsignments()||[],a=(null===(n=o[0])||void 0===n?void 0:n.availableShippingOptions)||[],d=a[0],c=a.find(e=>e.isRecommended);if((c||d)&&r){const e=(null==c?void 0:c.id)||d.id;yield this.paymentIntegrationService.selectShippingOption(e)}}})}getFastlaneStyles(e,t){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:i,isFastlaneStylingEnabled:r}=n.initializationData||{};return rd(r?i:{},null==t?void 0:t.styles)}}const sd=fi(e=>new ad(e,Cs(),nd()),[{id:"paypalcommerceacceleratedcheckout"},{id:"paypalcommercecreditcards"}]);function dd(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&void 0!==e.initializationData&&null!==e.initializationData&&"object"==typeof e.initializationData&&"stripePublishableKey"in e.initializationData&&"stripeConnectedAccount"in e.initializationData&&"shopperLanguage"in e.initializationData&&void 0!==e.initializationData.stripePublishableKey&&void 0!==e.initializationData.stripeConnectedAccount&&void 0!==e.initializationData.shopperLanguage}function cd(e){return"stripeLinkAuthenticationState"in e}class ld{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){var t,n,i,r,o;return n=this,i=void 0,o=function*(){let n;if(!e.stripeupe)throw new vi('Unable to proceed because "options" argument is not provided.');const{container:i,gatewayId:r,methodId:o,onEmailChange:a,getStyles:s,isLoading:d}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new vi(`Unable to proceed because "${e}" argument is not provided.`)}),yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:o}});const c=this.paymentIntegrationService.getState(),l=c.getPaymentMethodOrThrow(o,r),{clientToken:u}=l;if(!dd(l)||!u)throw new ni(ei.MissingPaymentToken);const{email:h}=c.getCustomerOrThrow(),p=c.getPaymentProviderCustomerOrThrow(),m=(cd(p)?p:{}).stripeLinkAuthenticationState;if(!h){let e;const r="function"==typeof s&&s();e=r?{variables:{colorPrimary:r.fieldInnerShadow,colorBackground:r.fieldBackground,colorText:r.labelText,colorDanger:r.fieldErrorText,colorTextSecondary:r.labelText,colorTextPlaceholder:r.fieldPlaceholderText},rules:{".Input":{borderColor:r.fieldBorder,color:r.fieldText,boxShadow:r.fieldInnerShadow}}}:{},n=yield this.scriptLoader.getStripeClient(l.initializationData,c.getCartLocale(),ka.V3,Fa,La),this._stripeElements=yield this.scriptLoader.getElements(n,{clientSecret:u,appearance:e});const{getBillingAddress:o,getConsignments:h}=this.paymentIntegrationService.getState(),p=h(),y=null===(t=null==p?void 0:p[0])||void 0===t?void 0:t.id,{email:g}=o()||{},f=g?{defaultValues:{mode:Ca.SHIPPING,email:g}}:{},v=this._stripeElements.getElement(Da.AUTHENTICATION)||this._stripeElements.create(Da.AUTHENTICATION,f);v.on(za.CHANGE,e=>{if(!("authenticated"in e))throw new ni(ei.MissingCustomer);this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:e.authenticated}),e.complete?a(e.authenticated,e.value.email):a(!1,""),d&&d(!1),void 0===m&&e.authenticated&&y&&this.paymentIntegrationService.deleteConsignment(y)}),v.mount(`#${i}`)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Da.AUTHENTICATION))||void 0===t||t.unmount(),Promise.resolve()}signIn(e,t){return this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()}signOut(e){return 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()}}const ud=fi(e=>new ld(e,new Ra(a())),[{id:"stripeupe"}]);var hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pd{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.isMounted=!1}deinitialize(){var e;null===(e=this.checkoutEventsUnsubscribe)||void 0===e||e.call(this),this.isMounted=!1}initCheckoutEventsSubscription(e,t,n,i){this.checkoutEventsUnsubscribe=this.paymentIntegrationService.subscribe(()=>hd(this,void 0,void 0,function*(){var r;const o=null==i?void 0:i.getElement(Da.PAYMENT);if(o){try{yield this.updateStripePaymentIntent(e,t)}catch(e){return this.isMounted&&(o.unmount(),this.isMounted=!1),void(e instanceof Error&&(null===(r=n.onError)||void 0===r||r.call(n,e)))}this.isMounted||(yield null==i?void 0:i.fetchUpdates(),this.mountElement(o,n.containerId))}}),e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.outstandingBalance},e=>{var t;return null===(t=e.getCheckout())||void 0===t?void 0:t.coupons})}mountElement(e,t){document.getElementById(t)&&(e.mount(`#${t}`),this.isMounted=!0)}mapAppearanceVariables(e){return{colorPrimary:e.fieldInnerShadow,colorBackground:e.fieldBackground,colorText:e.labelText,colorDanger:e.fieldErrorText,colorTextSecondary:e.labelText,colorTextPlaceholder:e.fieldPlaceholderText,colorIcon:e.fieldPlaceholderText}}mapInputAppearanceRules(e){return{borderColor:e.fieldBorder,color:e.fieldText,boxShadow:e.fieldInnerShadow}}throwStripeError(e){if("object"==typeof(t=e)&&null!==t&&"type"in t&&(this.throwDisplayableStripeError(e),this.isCancellationError(e)))throw new Wi;var t;throw new Qr}throwDisplayableStripeError(e){if(H(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}isCancellationError(e){var t;const n=null===(t=null==e?void 0:e.payment_intent.last_payment_error)||void 0===t?void 0:t.message;return!!n&&-1!==n.indexOf("canceled")}throwPaymentConfirmationProceedMessage(){throw new Qr("We've received your order and are processing your payment. Once the payment is verified, your order will be completed. We will send you an email when it's completed. Please note, this process may take a few minutes depending on the processing times of your chosen method.")}isPaymentCompleted(e,t){return hd(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(e),{features:r}=n.getStoreConfigOrThrow().checkoutSettings;if(!i.clientToken||!t||!r["PI-626.Block_unnecessary_payment_confirmation_for_StripeUPE"])return!1;const{paymentIntent:o}=yield t.retrievePaymentIntent(i.clientToken);return(null==o?void 0:o.status)===Ma.SUCCEEDED})}mapStripePaymentData(e,t,n=!1){const i=this.paymentIntegrationService.getState().getBillingAddress(),{firstName:r="",lastName:o="",email:a=""}=i||{},s=this.mapStripeAddress(i);if(!e)throw new ri(ti.PaymentNotInitialized);if(!(a&&s&&s.city&&s.country&&r&&o))throw new ni(ei.MissingBillingAddress);return{elements:e,redirect:Ta.IF_REQUIRED,confirmParams:Object.assign({payment_method_data:Object.assign(Object.assign({},n?{allow_redisplay:"always"}:{}),{billing_details:{email:a,address:s,name:this.getShopperFullName(i)}})},t&&{return_url:t})}}isAdditionalActionError(e){return fe(e,{code:"additional_action_required"})}isRedirectAction(e){const{type:t,data:{redirect_url:n}}=e;return"redirect_to_url"===t&&!!n}isOnPageAdditionalAction(e){const{type:t,data:{token:n}}=e;return"additional_action_requires_payment_method"===t&&!!n}updateStripePaymentIntent(e,t){return hd(this,void 0,void 0,function*(){const n=yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}}),{clientToken:i}=n.getPaymentMethodOrThrow(t);i&&this.scriptLoader.updateStripeElements({clientSecret:i})})}getStripeJsVersion(e){return e.useNewStripeJsVersion?ka.CLOVER:ka.V3}mapStripeAddress(e){if(e){const{city:t,address1:n,address2:i,countryCode:r,postalCode:o,stateOrProvinceCode:a}=e;return Object.assign({city:t,country:r,postal_code:o,line1:n,line2:i},a?{state:a}:{})}throw new ni(ei.MissingBillingAddress)}getShopperFullName(e){const{firstName:t="",lastName:n=""}=e||{};return`${t} ${n}`.trim()}}const md={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},yd={position:"fixed","background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},gd="embedded-checkout-loading-indicator-rotation";class fd{constructor(e){this.styles=Object.assign(Object.assign({},md),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=`${gd} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(n=>{e.style.setProperty(n,t[n])})}defineAnimation(){var e;if(document.getElementById(gd))return;const t=document.createElement("style");t.id=gd,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${gd} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}class vd{constructor(e){this._decimalPlaces=e}toInteger(e){return Math.round(e*Math.pow(10,this._decimalPlaces))}}const _d=["AC","AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CV","CW","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MK","ML","MM","MN","MO","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SZ","TA","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","US","UY","UZ","VA","VC","VE","VG","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW","ZZ"];var Sd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Id{constructor(e,t,n,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n,this.loadingIndicator=i}initialize(e){return Sd(this,void 0,void 0,function*(){const{stripeocs:t}=e||{};if(!t)throw new vi('Unable to proceed because "options" argument is not provided.');const{gatewayId:n,container:i}=t;if(!i||!n)throw new ri(ti.PaymentNotInitialized);const r=this._getMethodId(n),o=yield this.paymentIntegrationService.loadPaymentMethod(n,{params:{method:r}}),a=o.getPaymentMethodOrThrow(r,n),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!dd(a))throw new ni(ei.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this._mountExpressCheckoutElement(i,this._stripeClient,d),this._initializeEvents(r)})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,n=40){return Sd(this,void 0,void 0,function*(){const i=this._shouldRequireShippingAddress(),r=Object.assign(Object.assign(Object.assign({shippingAddressRequired:i},i?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),i?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ta.AUTO,applePay:Ta.NEVER,googlePay:Ta.NEVER,amazonPay:Ta.NEVER,paypal:Ta.NEVER,klarna:Ta.NEVER},buttonHeight:n}),{cartAmount:o}=this.paymentIntegrationService.getState().getCartOrThrow(),a=Object.assign({mode:"payment",amount:this._toCents(o),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});return this._stripeElements=t.elements(a),this._linkV2Element=this._stripeElements.create(Da.EXPRESS_CHECKOUT,r),this._linkV2Element.mount(`#${e}`),this._linkV2Element})}_initializeEvents(e){this._linkV2Element&&(this._shouldRequireShippingAddress()&&(this._linkV2Element.on(za.SHIPPING_ADDRESS_CHANGE,e=>Sd(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),this._linkV2Element.on(za.SHIPPING_RATE_CHANGE,e=>Sd(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),this._linkV2Element.on(za.CONFIRM,t=>Sd(this,void 0,void 0,function*(){return this._onConfirm(t,e)})),this._linkV2Element.on(za.CANCEL,this._onCancel))}_onShippingAddressChange(e){return Sd(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,n={firstName:"",lastName:"",phone:"",company:"",address1:"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.country)||"",postalCode:(null==t?void 0:t.postal_code)||"",stateOrProvince:(null==t?void 0:t.state)||"",stateOrProvinceCode:(null==t?void 0:t.state)||"",customFields:[]};yield this.paymentIntegrationService.updateShippingAddress(n);const i=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==i?void 0:i.length)?e.resolve({shippingRates:i}):e.reject()})}_onCancel(){throw new Wi}_onShippingRateChange(e){return Sd(this,void 0,void 0,function*(){if("shippingRate"in e){const{shippingRate:t}=e;yield this._handleShippingOptionChange(null==t?void 0:t.id),yield this._updateDisplayedPrice(),e.resolve({})}})}_onConfirm(e,t){return Sd(this,void 0,void 0,function*(){if("billingDetails"in e&&"shippingAddress"in e&&this._stripeClient&&this._stripeElements){yield this._updateShippingAndBillingAddress(e),yield this.paymentIntegrationService.submitOrder();const n=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(n)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,n,i,r,o,a,s,d;return Sd(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(n=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===n?void 0:n.split(" ")[0])||(null===(r=null===(i=e.billingDetails)||void 0===i?void 0:i.name)||void 0===r?void 0:r.split(" ")[0])||"",u=(null===(a=null===(o=e.shippingAddress)||void 0===o?void 0:o.name)||void 0===a?void 0:a.split(" ")[1])||(null===(d=null===(s=e.billingDetails)||void 0===s?void 0:s.name)||void 0===d?void 0:d.split(" ")[1])||"";if(c){const t=this._mapShippingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateShippingAddress(t)}const h=this._mapBillingAddress(e.shippingAddress,e.billingDetails,l,u);yield this.paymentIntegrationService.updateBillingAddress(h)})}_mapShippingAddress(e,t,n,i){var r,o,a,s,d,c,l;return{firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==e?void 0:e.address)||void 0===r?void 0:r.line1)||"",address2:(null===(o=null==e?void 0:e.address)||void 0===o?void 0:o.line2)||"",city:(null===(a=null==e?void 0:e.address)||void 0===a?void 0:a.city)||"",countryCode:(null===(s=null==e?void 0:e.address)||void 0===s?void 0:s.country)||"",postalCode:(null===(d=null==e?void 0:e.address)||void 0===d?void 0:d.postal_code)||"",stateOrProvince:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",stateOrProvinceCode:(null===(l=null==e?void 0:e.address)||void 0===l?void 0:l.state)||"",customFields:[]}}_mapBillingAddress(e,t,n,i){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:n,lastName:i,phone:(null==t?void 0:t.phone)||"",company:"",address1:(null===(r=null==t?void 0:t.address)||void 0===r?void 0:r.line1)||"",address2:"",city:(null===(o=null==t?void 0:t.address)||void 0===o?void 0:o.city)||"",countryCode:(null===(a=null==t?void 0:t.address)||void 0===a?void 0:a.country)||"",postalCode:(null===(s=null==t?void 0:t.address)||void 0===s?void 0:s.postal_code)||"",stateOrProvince:(null===(d=null==t?void 0:t.address)||void 0===d?void 0:d.state)||"",stateOrProvinceCode:(null===(c=null==e?void 0:e.address)||void 0===c?void 0:c.state)||"",customFields:[]}}_processAdditionalAction(e,t){return Sd(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new ri(ti.PaymentNotInitialized);const{data:n}=e.body.additional_action_required,{token:i}=n,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(n,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||i);try{this._toggleLoadingIndicator(!0),yield this.paymentIntegrationService.submitPayment(o),yield this._completeCheckoutFlow()}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}finally{this._toggleLoadingIndicator(!1)}})}_confirmStripePaymentOrThrow(e,t){var n,i,r;return Sd(this,void 0,void 0,function*(){const{token:o,redirect_url:a}=e,s=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,a);let d;try{const e=(yield this.stripeIntegrationService.isPaymentCompleted(t,this._stripeClient))?yield null===(r=this._stripeClient)||void 0===r?void 0:r.retrievePaymentIntent(o||""):yield null===(n=this._stripeClient)||void 0===n?void 0:n.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ta.IF_REQUIRED,confirmParams:{return_url:null===(i=s.confirmParams)||void 0===i?void 0:i.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Qr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return Sd(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var n;const i=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:i},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:Aa.Link})}}}_shouldRequireShippingAddress(){const{getCartOrThrow:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e();return!!t.physicalItems.length}_updateDisplayedPrice(){return Sd(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){if(!this._currencyCode){const{code:e}=this.paymentIntegrationService.getState().getCartOrThrow().currency;this._currencyCode=e.toLowerCase()}return this._currencyCode}_getTotalPrice(){return Sd(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:e,getCartOrThrow:t}=this.paymentIntegrationService.getState(),{decimalPlaces:n}=t().currency,i=ge(e().outstandingBalance,n).toFixed(n);return this._toCents(+i)})}_getAvailableCountries(){var e;return Sd(this,void 0,void 0,function*(){const t=yield this.paymentIntegrationService.loadShippingCountries();return((null===(e=t.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code))||[]).filter(e=>_d.includes(e))})}_getAvailableShippingOptions(){var e,t,n;return Sd(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const r=i[0],o=(r.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),a=null===(e=r.availableShippingOptions)||void 0===e?void 0:e.find(e=>e.isRecommended),s=null===(t=r.selectedShippingOption)||void 0===t?void 0:t.id,d=null==a?void 0:a.id;return s?o.sort(e=>e.id===s?-1:0):d?(o.sort(e=>e.id===d?-1:0),yield this._handleShippingOptionChange(d)):yield this._handleShippingOptionChange(null===(n=o[0])||void 0===n?void 0:n.id),o.slice(0,9)})}_getStripeShippingOption({id:e,cost:t,description:n}){return{id:e,displayName:n,amount:this._toCents(t)}}_handleShippingOptionChange(e){return Sd(this,void 0,void 0,function*(){if(e&&"shipping_option_unselected"!==e)return this.paymentIntegrationService.selectShippingOption(e)})}_getAmountTransformer(){if(this._amountTransformer)return this._amountTransformer;const{getCart:e}=this.paymentIntegrationService.getState(),{currency:t}=e()||{};return t?new vd(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),n=this._getAmountTransformer();return n?n.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}_getMethodId(e){const{initializationData:{checkoutSessionEnabled:t}={}}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return t?Aa.CHECKOUT_SESSION:Aa.OCS}}const wd=fi(e=>{const t=new Ra(a()),n=new fd({containerStyles:yd});return new Id(e,t,new pd(e,t),n)},[{id:"stripeocs"}]);class Cd extends Xn{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}class bd{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){yield this._paymentIntegrationService.submitOrder(le(e,"payment"),t)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Pd=fi(e=>new bd(e),[{id:"nopaymentdatarequired"}]);var Od,Ed,Ad,Td,kd,Dd,Md;class zd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-8ofgICZZ/k5cC5N7xegqFZOA73H9RQ7H13439JfAZW8Gj3qjuKL2isaTD3GMIhDE",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-wG2z9zSQo61EIvyXmiFCo+zB3y0ZB4hsrXVcANmpP8HLthjoQJQPBh7tZKJSV8jA",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return new this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function xd(e){return"object"==typeof e&&"string"==typeof e.data.paymentMethod.encryptedSecurityCode||"string"==typeof e.data.paymentMethod.encryptedExpiryMonth}function Nd(e){return Boolean(e.instrumentId)}!function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2="threeDS2",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher",e.Sdk="sdk"}(Od||(Od={})),function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2Challenge="threeDS2Challenge",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher"}(Ed||(Ed={})),function(e){e.SecuredFields="securedfields"}(Ad||(Ad={})),function(e){e.ACH="ach",e.AliPay="alipay",e.Bancontact="bcmc",e.CreditCard="scheme",e.Klarna="klarna",e.KlarnaPayNow="klarna_paynow",e.KlarnaAccount="klarna_account",e.IDEAL="ideal",e.GiroPay="giropay",e.GooglePay="paywithgoogle",e.SEPA="sepadirectdebit",e.Sofort="directEbanking",e.Vipps="vipps",e.WeChatPayQR="wechatpayQR"}(Td||(Td={})),function(e){e.POST="POST"}(kd||(kd={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(Dd||(Dd={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(Md||(Md={}));var Rd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return Rd(this,void 0,void 0,function*(){const{adyenv2:t}=e;if(!t)throw new vi('Unable to initialize payment because "options.adyenv2" argument is not provided.');this._paymentInitializeOptions=t;const n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{originKey:i,clientKey:r,environment:o,paymentMethodsResponse:a}=n.initializationData||{},s={key:"",value:""};return i?(s.key="originKey",s.value=i):(s.key="clientKey",s.value=r||""),this._adyenClient=yield this._scriptLoader.load({environment:o,locale:this._paymentIntegrationService.getState().getLocale(),[s.key]:s.value,paymentMethodsResponse:a,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this._paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){return Rd(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=n&&n.paymentData,o=r&&r.shouldSaveInstrument,a=r&&r.shouldSetAsDefaultInstrument;if(!n)return Promise.reject(new co(["payment"]));this._validateCardData(),yield this._paymentIntegrationService.submitOrder(i,t);const s=this._componentState;if(!s)throw new ri(ti.PaymentNotInitialized);if(r&&Nd(r)){let e={};if(xd(s)){const{encryptedCardNumber:t,encryptedSecurityCode:n,encryptedExpiryMonth:i,encryptedExpiryYear:r}=s.data.paymentMethod;e={credit_card_number_confirmation:t,expiry_month:i,expiry_year:r,verification_value:n}}if(xd(s)||-1!==["ideal","sepadirectdebit","directEbanking","giropay"].indexOf(s.data.paymentMethod.type))try{return void(yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:{formattedPayload:{bigpay_token:Object.assign(Object.assign({},e),{token:r.instrumentId}),origin:window.location.origin,browser_info:ss(),set_as_default_stored_instrument:a||null}}})))}catch(e){return void(yield this._processAdditionalAction(e,o,a))}}try{yield this._paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify(Object.assign(Object.assign({},s.data.paymentMethod),{origin:window.location.origin}))},browser_info:ss(),vault_payment_instrument:o||null,set_as_default_stored_instrument:a||null}}})}catch(e){yield this._processAdditionalAction(e,o,a)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._componentState=void 0,this._paymentComponent&&(this._paymentComponent.unmount(),this._paymentComponent=void 0),this._cardVerificationComponent&&(this._cardVerificationComponent.unmount(),this._cardVerificationComponent=void 0),Promise.resolve()}_getAdyenClient(){if(!this._adyenClient)throw new ri(ti.PaymentNotInitialized);return this._adyenClient}_getPaymentInitializeOptions(){if(!this._paymentInitializeOptions)throw new vi('"options.adyenv2" argument was not provided during initialization.');return this._paymentInitializeOptions}_getThreeDS2ChallengeWidgetSize(){const{additionalActionOptions:e,threeDS2Options:t}=this._getPaymentInitializeOptions();return e.widgetSize||(null==t?void 0:t.widgetSize)||"05"}_handleAction(e){return new Promise((t,n)=>{const{threeDS2ContainerId:i,additionalActionOptions:r}=this._getPaymentInitializeOptions(),{onBeforeLoad:o,containerId:a,onLoad:s,onComplete:d}=r,c=JSON.parse(e.action),l=this._getAdyenClient().createFromAction(c,{onAdditionalDetails:e=>{const n={methodId:c.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};d&&d(),t(n)},size:this._getThreeDS2ChallengeWidgetSize(),onError:e=>n(e)});o&&o(c.type===Ed.ThreeDS2Challenge||c.type===Ed.QRCode),l.mount(`#${a||i}`),s&&s(()=>{n(new Wi),l.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let n;return new Promise((i,r)=>{var o,a,s;if(e.cardVerificationContainerId){n=t.create(Ad.SecuredFields,Object.assign(Object.assign({},e.options),{styles:Object.assign(Object.assign({},null===(o=e.options)||void 0===o?void 0:o.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(s=null===(a=e.options)||void 0===a?void 0:a.styles)||void 0===s?void 0:s.placeholder)}),onChange:e=>this._updateComponentState(e),onError:t=>e.validateCardFields(t),onFieldValid:t=>e.validateCardFields(t)}));try{n.mount(`#${e.cardVerificationContainerId}`)}catch(e){r(new ri(ti.PaymentNotInitialized))}}i(n)})}_mountPaymentComponent(e){let t;const n=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((r,o)=>{switch(e.method){case Td.CreditCard:case Td.ACH:case Td.Bancontact:{const r=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:a}=e.initializationData;t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e),data:this._mapAdyenPlaceholderData(r,a)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ti.PaymentNotInitialized))}break}case Td.IDEAL:case Td.SEPA:if(n.hasVaultedInstruments)this._updateComponentState({data:{paymentMethod:{type:e.method}}});else{t=i.create(e.method,Object.assign(Object.assign({},n.options),{onChange:e=>this._updateComponentState(e)}));try{t.mount(`#${n.containerId}`)}catch(e){o(new ri(ti.PaymentNotInitialized))}}break;case Td.AliPay:case Td.GiroPay:case Td.Sofort:case Td.Klarna:case Td.KlarnaPayNow:case Td.KlarnaAccount:case Td.Vipps:case Td.WeChatPayQR:this._updateComponentState({data:{paymentMethod:{type:e.method}}})}r(t)})}_processAdditionalAction(e,t,n){return Rd(this,void 0,void 0,function*(){if(!pa(e)||!fe(e.body.errors,{code:"additional_action_required"}))throw e;const i=yield this._handleAction(e.body.provider_data);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},i.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n})}))}catch(e){return this._processAdditionalAction(e,t,n)}})}_updateComponentState(e){this._componentState=e}_validateCardData(){var e,t;const n=this._getPaymentInitializeOptions().hasVaultedInstruments?this._cardVerificationComponent:this._paymentComponent;if((null===(e=null==n?void 0:n.componentRef)||void 0===e?void 0:e.showValidation)&&n.state&&(n.componentRef.showValidation(),0===Object.keys(n.state).length||!n.state.isValid&&!n.state.issuer||"sepadirectdebit"===(null===(t=n.props)||void 0===t?void 0:t.type)&&n.state.data&&Object.values(n.state.data).some(e=>0===e.toString().trim().length)))throw new lo(this._mapCardErrors(n.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}}const Ld=fi(e=>new Fd(e,new zd(a(),s())),[{gateway:"adyenv2"}]);class jd{constructor(e,t,n=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}load(e){var t,n,i,r,o,a;return i=this,r=void 0,a=function*(){if(yield Promise.all([this._stylesheetLoader.loadStylesheet(`https://checkoutshopper-${null!==(t=e.environment)&&void 0!==t?t:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.css`,{prepend:!1,attributes:{integrity:"sha384-5MvB4RnzvviA3VBT4KYABZ4HXNZG5LRqREEgd41xt/pf/QvKmsj2O9GuNuywRXx9",crossorigin:"anonymous"}}),this._scriptLoader.loadScript(`https://checkoutshopper-${null!==(n=e.environment)&&void 0!==n?n:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new mi;return yield this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}}function Bd(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}var Ud=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class qd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return Ud(this,void 0,void 0,function*(){const{adyenv3:t}=e;if(!t)throw new vi('Unable to initialize payment because "options.adyenv3" argument is not provided.');this._paymentInitializeOptions=t;const n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{environment:i,clientKey:r,paymentMethodsResponse:o,installmentOptions:a}=n.initializationData||{};return this._adyenClient=yield this._scriptLoader.load({paymentMethodsConfiguration:Object.assign({klarna:{useKlarnaWidget:!0},klarna_account:{useKlarnaWidget:!0},klarna_paynow:{useKlarnaWidget:!0}},a?{card:{installmentOptions:Object.assign({showInstallmentAmounts:!0},a)}}:{}),environment:i,locale:this._getLocale(),clientKey:r,paymentMethodsResponse:o,showPayButton:!1,translations:{es:{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-AR":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-ES":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-MX":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CL":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-CO":{"creditCard.expiryDateField.title":"Fecha de caducidad"},"es-PE":{"creditCard.expiryDateField.title":"Fecha de caducidad"}}}),this._paymentComponent=yield this._mountPaymentComponent(n),n.method!==Td.CreditCard&&n.method!==Td.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){var n;return Ud(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!i)throw new co(["payment"]);const o=i.paymentData,{shouldSaveInstrument:a,shouldSetAsDefaultInstrument:s}=Bd(o)?o:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};this._validateCardData(),"klarna"!==i.methodId&&"klarna_account"!==i.methodId&&"klarna_paynow"!==i.methodId||null===(n=this._paymentComponent)||void 0===n||n.submit(),yield this._paymentIntegrationService.submitOrder(r,t);const d=this._componentState||{data:{paymentMethod:{type:i.methodId}}};if(o&&Nd(o)){let e={};if(xd(d)){const{encryptedCardNumber:t,encryptedSecurityCode:n,encryptedExpiryMonth:i,encryptedExpiryYear:r}=d.data.paymentMethod;e={credit_card_number_confirmation:t,expiry_month:i,expiry_year:r,verification_value:n}}try{return void(yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:{formattedPayload:{bigpay_token:Object.assign(Object.assign({},e),{token:o.instrumentId}),origin:window.location.origin,browser_info:ss(),set_as_default_stored_instrument:s||null}}})))}catch(t){return void(yield this._processAdditionalAction(t,a,s,o.instrumentId,e))}}let c=JSON.stringify(Object.assign(Object.assign({},d.data.paymentMethod),{type:i.methodId,origin:window.location.origin}));"boletobancario"===i.methodId&&function(e){var t,n;return"string"===("object"==typeof e&&typeof e.data.socialSecurityNumber)&&"string"==typeof(null===(t=e.data.shopperName)||void 0===t?void 0:t.firstName)&&"string"==typeof(null===(n=e.data.shopperName)||void 0===n?void 0:n.lastName)}(d)&&(c=JSON.stringify(Object.assign(Object.assign({socialSecurityNumber:d.data.socialSecurityNumber},d.data.shopperName),{type:i.methodId,origin:window.location.origin})));try{yield this._paymentIntegrationService.submitPayment({methodId:i.methodId,paymentData:{formattedPayload:Object.assign(Object.assign({credit_card_token:{token:c}},xd(d)&&d.data.installments?{installments:{value:d.data.installments.value,plan:d.data.installments.plan||"regular"}}:{}),{browser_info:ss(),vault_payment_instrument:a||null,set_as_default_stored_instrument:s||null})}})}catch(e){yield this._processAdditionalAction(e,a,s)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._componentState=void 0,this._paymentComponent&&(this._paymentComponent.unmount(),this._paymentComponent=void 0),this._cardVerificationComponent&&(this._cardVerificationComponent.unmount(),this._cardVerificationComponent=void 0),Promise.resolve()}_updateComponentState(e){this._componentState=e}_getLocale(){const e=this._paymentIntegrationService.getState().getLocale();return e&&"es"===e.substring(0,2)?"es":e}_getAdyenClient(){if(!this._adyenClient)throw new ri(ti.PaymentNotInitialized);return this._adyenClient}_getPaymentInitializeOptions(){if(!this._paymentInitializeOptions)throw new vi('"options.adyenv3" argument was not provided during initialization.');return this._paymentInitializeOptions}_handleAction(e){return new Promise((t,n)=>{const{additionalActionOptions:i}=this._getPaymentInitializeOptions(),{onBeforeLoad:r,containerId:o,onLoad:a,onComplete:s,widgetSize:d,onActionHandled:c}=i,l=JSON.parse(e.action),u=this._getAdyenClient().createFromAction(l,{onActionHandled:e=>{c&&"function"==typeof c&&"3DS2Fingerprint"!==e.componentType&&c()},onAdditionalDetails:e=>{const n={methodId:l.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};s&&"function"==typeof s&&s(),t(n)},challengeWindowSize:d||"05",onError:e=>n(e)});r&&"function"==typeof r&&r(l.type===Od.ThreeDS2||l.type===Od.QRCode||l.type===Od.Sdk),this._mountElement(u,o),a&&"function"==typeof a&&a(()=>{n(new Wi),u.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:n,lastName:i,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${n} ${i}`:"",firstName:t?n:"",lastName:t?i:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let n;return new Promise((i,r)=>{var o,a,s;if(e.cardVerificationContainerId){n=t.create(Ad.SecuredFields,Object.assign(Object.assign({},e.options),{styles:Object.assign(Object.assign({},null===(o=e.options)||void 0===o?void 0:o.styles),{placeholder:Object.assign({color:"transparent",caretColor:"#000"},null===(s=null===(a=e.options)||void 0===a?void 0:a.styles)||void 0===s?void 0:s.placeholder)}),onChange:e=>this._updateComponentState(e),onError:t=>e.validateCardFields(t),onFieldValid:t=>e.validateCardFields(t)}));try{this._mountElement(n,e.cardVerificationContainerId)}catch(e){r(new ri(ti.PaymentNotInitialized))}}i(n)})}_mountPaymentComponent(e){let t;const n=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((r,o)=>{const a=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:s}=e.initializationData;t=i.create(e.method,Object.assign(Object.assign(Object.assign({},n.options),{showBrandsUnderCardNumber:!1,billingAddressRequired:!1,showEmailAddress:!1,onChange:e=>this._updateComponentState(e),onSubmit:e=>this._updateComponentState(e)}),a?{data:this._mapAdyenPlaceholderData(a,s)}:{}));try{this._mountElement(t,n.containerId)}catch(e){o(new ri(ti.PaymentNotInitialized))}r(t)})}_processAdditionalAction(e,t,n,i,r){return Ud(this,void 0,void 0,function*(){if(!pa(e)||!fe(e.body.errors,{code:"additional_action_required"}))throw e;const o=yield this._handleAction(e.body.provider_data);try{const e=Object.assign(Object.assign({},o.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n}),a=n&&!t?{instrumentId:i,formattedPayload:{bigpay_token:Object.assign(Object.assign({},r),{token:i})}}:{};yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},o),{paymentData:Object.assign(Object.assign({},e),a)}))}catch(e){return this._processAdditionalAction(e,t,n,i,r)}})}_validateCardData(){var e;const t=this._getPaymentInitializeOptions().hasVaultedInstruments?this._cardVerificationComponent:this._paymentComponent;if((null===(e=null==t?void 0:t.componentRef)||void 0===e?void 0:e.showValidation)&&t.state&&(t.componentRef.showValidation(),0===Object.keys(t.state).length||!t.state.isValid))throw new lo(this._mapCardErrors(t.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(n=>{t[n]=[{message:e[n],type:n}]}),t}_mountElement(e,t){document.getElementById(t)&&e.mount(`#${t}`)}}const Vd=fi(e=>new qd(e,new jd(a(),s())),[{gateway:"adyenv3"}]);var Gd,Hd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wd{constructor(e,t){this.paymentIntegrationService=e,this.affirmScriptLoader=t}initialize(e){return Hd(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e.methodId);const t=this.paymentIntegrationService.getState(),{clientToken:n,config:{testMode:i}}=t.getPaymentMethodOrThrow(e.methodId);if(!n)throw new ni(ei.MissingPaymentMethod);this.affirm=yield this.affirmScriptLoader.load(n,i)})}execute(e,t){var n;return Hd(this,void 0,void 0,function*(){const i=null===(n=e.payment)||void 0===n?void 0:n.methodId,{useStoreCredit:r}=e;if(!this.affirm)throw new ri(ti.PaymentNotInitialized);if(!i)throw new co(["payment.methodId"]);yield this.paymentIntegrationService.submitOrder({useStoreCredit:r},t);const o={methodId:i,paymentData:{nonce:(yield this.initializeAffirmCheckout()).checkout_token}};yield this.paymentIntegrationService.submitPayment(o)})}deinitialize(){return this.affirm&&(this.affirm=void 0),Promise.resolve()}finalize(){return Promise.reject(new Cd)}initializeAffirmCheckout(){var e;return null===(e=this.affirm)||void 0===e||e.checkout(this.getCheckoutInformation()),new Promise((e,t)=>{var n,i;null===(n=this.affirm)||void 0===n||n.checkout.open({onFail:e=>{"canceled"===e.reason?t(new Wi):t(new Xr)},onSuccess:t=>{e(t)}}),null===(i=this.affirm)||void 0===i||i.ui.error.on("close",()=>{t(new Wi)})})}getCheckoutInformation(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfig(),n=e.getConsignments(),i=e.getOrder(),r=e.getCart();if(!t)throw new ni(ei.MissingCheckoutConfig);if(!i)throw new ni(ei.MissingCheckout);const o=new vd(i.currency.decimalPlaces),a=this.getBillingAddress(),s=this.getShippingAddress(),d=Bo(r,t)&&s?s:a;return{merchant:{user_confirmation_url:t.links.checkoutLink,user_cancel_url:t.links.checkoutLink,user_confirmation_url_action:"POST"},shipping:d,billing:a,items:this.getItems(o,i),metadata:{shipping_type:this.getShippingType(n),mode:"modal",platform_type:"BigCommerce",platform_version:"",platform_affirm:""},discounts:this.getDiscounts(o,i),order_id:i.orderId?i.orderId.toString():"",shipping_amount:o.toInteger(i.shippingCostTotal),tax_amount:o.toInteger(i.taxTotal),total:o.toInteger(i.orderAmount)}}getShippingType(e){if(!e)return"";const t=e[0];return(null==t?void 0:t.selectedShippingOption)?t.selectedShippingOption.type:""}getBillingAddress(){const e=this.paymentIntegrationService.getState().getBillingAddress();if(!e)throw new ni(ei.MissingBillingAddress);return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone,email:e.email}}getShippingAddress(){const e=this.paymentIntegrationService.getState().getShippingAddress();if(e)return{name:{first:e.firstName,last:e.lastName,full:`${e.firstName} ${e.lastName}`},address:{line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,zipcode:e.postalCode,country:e.countryCode},phone_number:e.phone}}getItems(e,t){const n=[];return t.lineItems.physicalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.digitalItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.salePrice),qty:t.quantity,item_image_url:t.imageUrl,item_url:t.url,categories:this.getCategories(t.categories)})}),t.lineItems.giftCertificates.forEach(t=>{n.push({display_name:t.name,sku:"",unit_price:e.toInteger(t.amount),qty:1,item_image_url:"",item_url:""})}),t.lineItems.customItems&&t.lineItems.customItems.forEach(t=>{n.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.listPrice),qty:t.quantity,item_image_url:"",item_url:""})}),n}getDiscounts(e,t){const n={};return t.coupons.forEach(t=>{t.discountedAmount>0&&(n[t.code]={discount_amount:e.toInteger(t.discountedAmount),discount_display_name:t.displayName})}),t.discountAmount>0&&(n.DISCOUNTED_AMOUNT={discount_amount:e.toInteger(t.discountAmount),discount_display_name:"discount"}),n}getCategories(e){return e?e.map(e=>e.map(e=>e.name)):[[]]}}!function(e){e.PROD="//cdn1.affirm.com/js/v2/affirm.js",e.SANDBOX="//cdn1-sandbox.affirm.com/js/v2/affirm.js"}(Gd||(Gd={}));class $d{constructor(e=window){this.affirmWindow=e}load(e="",t){const n=t?Gd.SANDBOX:Gd.PROD;if(function(e,t,n,i,r,o,a){const s=e[n]||{},d=document.createElement(o),c=document.getElementsByTagName(o)[0],l=function(e,t,n){return function(){e[t]._.push([n,arguments])}};s[i]=l(s,i,"set");const u=s[i];s[r]={},s[r]._=[],u._=[],s._=[],s[r][a]=l(s,r,a),s.jsReady=function(){s._.push([a,arguments])};let h=0;for(const e="set add save post open empty reset on off trigger ready setProduct".split(" ");h<e.length;h++)u[e[h]]=l(s,i,e[h]);let p=0;for(const e=["get","token","url","items"];p<e.length;p++)u[e[p]]=function(){};d.async=!0,d.src=t[o],c.parentNode&&c.parentNode.insertBefore(d,c),delete t[o],u(t),e[n]=s}(window,{public_api_key:e,script:n},"affirm","checkout","ui","script","ready"),!this.affirmWindow.affirm)throw new mi;return Promise.resolve(this.affirmWindow.affirm)}}const Yd=fi(e=>new Wd(e,new $d),[{id:"affirm"}]);class Kd extends Xn{constructor(e){super(e||"The current order could not be finalized successfully"),this.name="OrderFinalizationNotCompletedError",this.type="order_finalization_not_completed"}}var Jd=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zd{constructor(e,t){this._paymentIntegrationService=e,this._afterpayScriptLoader=t}initialize(e){var t;return Jd(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethod(e.methodId,e.gatewayId),r=(null===(t=n.getCart())||void 0===t?void 0:t.currency.code)||"",o=this._mapCurrencyToISO2(r),a=Ci(n.getStoreConfigOrThrow().checkoutSettings.features,"PI-4789.afterpay_script_use_https",!1);if(!i)throw new ni(ei.MissingPaymentMethod);this._afterpaySdk=yield this._afterpayScriptLoader.load(i,o,a)})}deinitialize(){return this._afterpaySdk&&(this._afterpaySdk=void 0),Promise.resolve()}execute(e,t){var n;return Jd(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment.gatewayId","payment.methodId"]);const{gatewayId:i,methodId:r}=e.payment;if(!i||!r)throw new co(["payment.gatewayId","payment.methodId"]);const{useStoreCredit:o}=e;void 0!==o&&(yield this._paymentIntegrationService.applyStoreCredit(o)),yield this._loadPaymentMethod(i,r,t);const a=this._paymentIntegrationService.getState();yield this._paymentIntegrationService.validateCheckout(a.getCheckout(),t);const s=(null===(n=a.getCart())||void 0===n?void 0:n.currency.code)||"",d=this._mapCurrencyToISO2(s);return this._redirectToAfterpay(d,a.getPaymentMethod(r,i)),new Promise(()=>{})})}finalize(e){var t,n,i;return Jd(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ni(ei.MissingCheckout);if(!(null==a?void 0:a.payment.token))throw new ni(ei.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToAfterpay(e,t){if(!this._afterpaySdk||!(null==t?void 0:t.clientToken))throw new ri(ti.PaymentNotInitialized);this._afterpaySdk.initialize({countryCode:e}),this._afterpaySdk.redirect({token:t.clientToken})}_mapCurrencyToISO2(e){return{AUD:"AU",NZD:"NZ",CAD:"CA",USD:"US"}[e]||"AU"}_loadPaymentMethod(e,t,n){var i;return Jd(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new vi("Afterpay can't process your payment for this order, please try another payment method");throw e}})}}var Qd,Xd;!function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Qd||(Qd={})),function(e){e.PROD="//portal.afterpay.com/afterpay-async.js",e.SANDBOX="//portal.sandbox.afterpay.com/afterpay.js",e.HTTPS_PROD="https://portal.afterpay.com/afterpay-async.js",e.HTTPS_SANDBOX="https://portal.sandbox.afterpay.com/afterpay.js"}(Xd||(Xd={}));class ec{constructor(e){this._scriptLoader=e}load(e,t,n=!1){return i=this,r=void 0,a=function*(){const i=e.config.testMode||!1,r=this._getScriptURI(t,i,n);return this._scriptLoader.loadScript(r).then(()=>{if(!function(e){return"AfterPay"in e}(window))throw new mi;return window.AfterPay})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}_getScriptURI(e,t,n=!1){return"US"===e?n?t?Xd.HTTPS_SANDBOX:Xd.HTTPS_PROD:t?Xd.SANDBOX:Xd.PROD:n?t?Qd.HTTPS_SANDBOX:Qd.HTTPS_PROD:t?Qd.SANDBOX:Qd.PROD}}const tc=fi(e=>new Zd(e,new ec(o())),[{gateway:"afterpay"},{id:"afterpay"}]);var nc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ic{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return nc(this,void 0,void 0,function*(){const{methodId:t,amazonpay:n}=e;if(!t)throw new vi('Unable to proceed because "methodId" argument is not provided.');const i=this.paymentIntegrationService.getState(),{features:r}=i.getStoreConfigOrThrow().checkoutSettings,o=i.getPaymentMethodOrThrow(t),a=o.initializationData||{},{paymentToken:s="",region:d="",isButtonMicroTextDisabled:c}=a;if(yield this.amazonPayV2PaymentProcessor.initialize(o),this._isReadyToPay(s))(null==n?void 0:n.editButtonId)&&this._bindEditButton(n.editButtonId,s,"changePayment",this._isModalFlow(d));else{const{id:e}=this._createContainer();if(this._amazonPayButton=this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:i,containerId:e,decoupleCheckoutInitiation:this._isOneTimeTransaction(r,d.toUpperCase()),methodId:t,placement:si.Checkout,isButtonMicroTextDisabled:c}),!this._amazonPayButton)throw new vi("Unable to render the Amazon Pay button to an invalid HTML container element.")}})}execute(e,t){return nc(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);const{methodId:i}=n,r=this.paymentIntegrationService.getState(),{features:o}=r.getStoreConfigOrThrow().checkoutSettings,a=r.getPaymentMethodOrThrow(i).initializationData||{},{paymentToken:s="",region:d=""}=a;if(this._isReadyToPay(s)||this._isOneTimeTransaction(o,d.toUpperCase())){const n={methodId:i,paymentData:{nonce:s||"apb"}};yield this.paymentIntegrationService.submitOrder(e,t);try{return void(yield this.paymentIntegrationService.submitPayment(n))}catch(e){if(!(pa(e)&&(c=e.body,"object"==typeof c&&null!==c&&"status"in c&&"additional_action_required"in c&&"additional_action_required"===c.status&&"data"in c.additional_action_required&&"redirect_url"in c.additional_action_required.data&&"string"==typeof c.additional_action_required.data.redirect_url)))throw e;const{additional_action_required:t}=e.body,{redirect_url:n}=t.data;if(s)return new Promise(()=>window.location.assign(n));this.amazonPayV2PaymentProcessor.prepareCheckout(JSON.parse(n))}}var c;return this._getAmazonPayButton().click(),this._isModalFlow(d)?new Promise((e,t)=>{const n=()=>{window.removeEventListener("focus",n),t(new Wi("Shopper needs to login to Amazonpay to continue"))};window.addEventListener("focus",n)}):new Promise(ce)})}finalize(){return Promise.reject(new Cd)}deinitialize(){return nc(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize(),this._amazonPayButton=void 0})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(!i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>{this._showLoadingSpinner()})}this.amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_isModalFlow(e){return"us"===e}_showLoadingSpinner(){return nc(this,void 0,void 0,function*(){yield this.paymentIntegrationService.widgetInteraction(()=>new Promise(ce))})}_createContainer(){let e=document.getElementById("AmazonPayButton");return e||(e=document.createElement("div"),e.id="AmazonPayButton",e.style.display="none",document.body.appendChild(e))}_getAmazonPayButton(){return ii(this._amazonPayButton,()=>new ri(ti.PaymentNotInitialized))}_isOneTimeTransaction(e,t){return this.amazonPayV2PaymentProcessor.isPh4Enabled(e,t)&&e["INT-6399.amazon_pay_apb"]}_isReadyToPay(e){return!!e}}const rc=fi(e=>new ic(e,gi()),[{id:"amazonpay"}]);var oc,ac=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.Shipping="Shipping",e.Subtotal="Subtotal",e.StoreCredit="Store Credit"}(oc||(oc={}));class sc{constructor(e,t,n,i,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._braintreeSdk=i,this._applePayScriptLoader=r,this._shippingLabel=oc.Shipping,this._subTotalLabel=oc.Subtotal,this._storeCreditLabel=oc.StoreCredit}initialize(e){var t,n,i,r;return ac(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new vi('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:o}=e;yield this._applePayScriptLoader.loadSdk(),this._shippingLabel=(null===(t=e.applepay)||void 0===t?void 0:t.shippingLabel)||oc.Shipping,this._subTotalLabel=(null===(n=e.applepay)||void 0===n?void 0:n.subtotalLabel)||oc.Subtotal,this._storeCreditLabel=(null===(i=e.applepay)||void 0===i?void 0:i.storeCreditLabel)||oc.StoreCredit;const a=(yield this._paymentIntegrationService.loadPaymentMethod(o)).getPaymentMethodOrThrow(o);(null===(r=a.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&a.clientToken&&this._braintreeSdk.initialize(a.clientToken)})}execute(e,t){return ac(this,void 0,void 0,function*(){const{payment:n}=e,i=this._paymentIntegrationService.getState();if(!n)throw new co(["payment"]);const{methodId:r}=n,o=i.getPaymentMethodOrThrow(r),a=this._getBaseRequest(i,o),s=this._sessionFactory.create(a);return yield this._paymentIntegrationService.submitOrder({useStoreCredit:e.useStoreCredit},t),s.begin(),new Promise((e,t)=>{this._handleApplePayEvents(s,o,{resolve:e,reject:t})})})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_getBaseRequest(e,t){const n=e.getCheckoutOrThrow(),i=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),{storeProfile:{storeCountryCode:o,storeName:a}}=r,{currency:{code:s,decimalPlaces:d}}=i,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=t,{grandTotal:u,isStoreCreditApplied:h,outstandingBalance:p}=n,m=[{label:this._subTotalLabel,amount:`${n.subtotal.toFixed(d)}`}];if(n.taxes.forEach(e=>m.push({label:e.name,amount:`${e.amount.toFixed(d)}`})),m.push({label:this._shippingLabel,amount:`${n.shippingCostTotal.toFixed(d)}`}),h){const{storeCredit:t}=e.getCustomerOrThrow();m.push({label:this._storeCreditLabel,amount:`-${Math.min(u,t).toFixed(d)}`})}return{countryCode:o,currencyCode:s,merchantCapabilities:c,supportedNetworks:l,lineItems:m,total:{label:a,amount:`${p.toFixed(d)}`,type:"final"}}}_handleApplePayEvents(e,t,n){e.onvalidatemerchant=n=>ac(this,void 0,void 0,function*(){try{const{body:i}=yield this._onValidateMerchant(t,n);e.completeMerchantValidation(i)}catch(e){throw new Error("Merchant validation failed")}}),e.oncancel=()=>ac(this,void 0,void 0,function*(){return n.reject(new Wi("Continue with applepay"))}),e.onpaymentauthorized=i=>this._onPaymentAuthorized(i,e,t,n)}_onValidateMerchant(e,t){return ac(this,void 0,void 0,function*(){const n=[`validationUrl=${t.validationURL}`,`merchantIdentifier=${e.initializationData.merchantId}`,`displayName=${e.initializationData.storeName}`,`domainName=${window.location.hostname}`].join("&");return this._requestSender.post(`${e.initializationData.paymentsUrl}/api/public/v1/payments/applepay/validate_merchant`,{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})})}_onPaymentAuthorized(e,t,n,i){var r;return ac(this,void 0,void 0,function*(){const{token:o}=e.payment;let a;(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)===Vi.BRAINTREE&&(a=yield this._getBraintreeDeviceData());const s={methodId:n.id,paymentData:{deviceSessionId:a,formattedPayload:{apple_pay_token:{payment_data:o.paymentData,payment_method:o.paymentMethod,transaction_id:o.transactionIdentifier}}}};try{return yield this._paymentIntegrationService.submitPayment(s),t.completePayment(ApplePaySession.STATUS_SUCCESS),i.resolve()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),i.reject(new ri(ti.PaymentNotInitialized))}})}_getBraintreeDeviceData(){return ac(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const dc=fi(e=>{const{getHost:t}=e.getState(),i=new Ei(e);return new sc(n({host:t()}),e,new Zi,new Ui(new Hi(a(),window,i)),new Qi(new r))},[{id:"applepay"}]),cc={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},lc=function({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};function uc(e){return"object"==typeof e&&null!==e&&"bigpayToken"in e&&"defaultInstrument"in e&&"provider"in e&&"trustedShippingAddress"in e&&"method"in e&&"type"in e}var hc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class pc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.paypalSdkHelper=n,this.loadingIndicator=i}initialize(e){return hc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments:n}=e||{};if(this.bigcommerce_payments=n,!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new vi('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{container:o,bannerContainerId:a}=n,{orderId:s,paypalBNPLConfiguration:d=[],isPayPalCreditAvailable:c}=r.initializationData||{};if(void 0!==a){if(!document.getElementById(a))return void console.error("Unable to create banner without valid banner container ID.");const e=null==d?void 0:d.find(({id:e})=>"checkout"===e);if(c||!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,a,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}s?this.orderId=s:(this.loadingIndicatorContainer=null==o?void 0:o.split("#")[1],yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),n.onInit&&"function"==typeof n.onInit&&n.onInit(()=>this.renderButton(t,n)),(void 0===n.shouldRenderPayPalButtonOnInitialization||n.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(t,n))})}execute(e,t){return hc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{onError:r}=this.bigcommerce_payments||{};if(!n)throw new co(["payment"]);const{methodId:o,paymentData:a}=n;if(this.isPayPalVaultedInstrumentPaymentData(a)&&!this.orderId&&(this.orderId=yield this.createOrder()),!this.orderId)throw new Xr;const s=this.isPayPalVaultedInstrumentPaymentData(a)?this.prepareVaultedInstrumentPaymentPayload(o,this.orderId,a):this.preparePaymentPayload(o,this.orderId,a);try{yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment(s)}catch(e){return this.isProviderError(e)&&(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n.methodId),yield new Promise((e,t)=>{var i;this.bigcommerce_payments&&(null===(i=this.paypalButton)||void 0===i||i.close(),this.renderButton(n.methodId,this.bigcommerce_payments),this.handleError(new Error("INSTRUMENT_DECLINED"),r)),t()})),this.handleError(e,r),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=Bd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new vi('Unable to initialize payment because "container" argument is not provided.');const y=Object.assign(Object.assign({},this.isAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(y),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return hc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return hc(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_paymentscheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.bigcommerce_payments||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&Nd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&Nd(e)&&Bd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isAppSwitchEnabled(e){var t,n;return null!==(n=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==n&&n}}const mc=fi(e=>new pc(e,Sr(e),Rr(),new fd({containerStyles:cc})),[{id:"bigcommerce_payments"}]);function yc(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var gc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsRequestSender=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){var t,n;return gc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_fastlane:r}=e;if(!i)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(this.methodId=i,!r)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_fastlane" argument is not provided.');if(this.bigcommerce_payments_fastlane=r,!r.onInit||"function"!=typeof r.onInit)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(s,a.currency.code,a.id);const l=qr(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return gc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{paymentData:r,methodId:o}=n,a=r&&Nd(r);try{yield this.paymentIntegrationService.submitOrder(i,t);const e=a?yield this.prepareVaultedInstrumentPaymentPayload(o,r):yield this.preparePaymentPayload(o,r);yield this.paymentIntegrationService.submitPayment(e),this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId()}catch(e){if(function(e){return"object"==typeof e&&null!==e&&"message"in e&&"response"in e&&"name"in e.response}(e)&&"INVALID_REQUEST"===e.response.name){const e={translationKey:"payment.errors.invalid_request_error"};return this.handleError(e),Promise.reject()}if(e instanceof Error&&"FastlaneError"!==e.name)throw e;return Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return gc(this,void 0,void 0,function*(){return Promise.resolve()})}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getCustomerOrThrow(),i=e.getPaymentProviderCustomer(),r=yc(i)?i:{},o=this.bigCommercePaymentsFastlaneUtils.getStorageSessionId();return!(!n.isGuest||(null==r?void 0:r.authenticationState)===zr.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}runPayPalAuthenticationFlowOrThrow(e){return gc(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),{authenticationState:d,addresses:c,instruments:l}=this.bigCommercePaymentsFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,s);yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:d,addresses:c,instruments:l}),s.authenticationState===zr.CANCELED?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(n.id)}catch(e){}})}initializePayPalPaymentComponent(){return gc(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),t=e.phone,n=`${e.firstName} ${e.lastName}`.trim(),i=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),r={fields:Object.assign({cardholderName:{prefill:n,enabled:!0}},t&&{phoneNumber:{prefill:t}})};this.paypalComponentMethods=yield i.FastlaneCardComponent(r)})}renderPayPalPaymentComponent(e){const t=this.getPayPalComponentMethodsOrThrow();if(!e)throw new vi('Unable to render card component because "container" argument is not provided.');t.render(e)}getPayPalComponentMethodsOrThrow(){if(!this.paypalComponentMethods)throw new mi;return this.paypalComponentMethods}prepareVaultedInstrumentPaymentPayload(e,t){return gc(this,void 0,void 0,function*(){const{instrumentId:n}=t,i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),r=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&i.config.is3dsEnabled?yield this.get3DSNonce(n):n;return yield this.createOrder(r),{methodId:e,paymentData:{formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:r}}}}})}preparePaymentPayload(e,t){return gc(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getBillingAddressOrThrow(),r=n.getPaymentMethodOrThrow(e),o=`${i.firstName} ${i.lastName}`.trim(),{getPaymentToken:a}=this.getPayPalComponentMethodsOrThrow(),{id:s}=yield a({name:{fullName:o},billingAddress:this.bigCommercePaymentsFastlaneUtils.mapBcToPayPalAddress(i)}),d=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&r.config.is3dsEnabled,{shouldSaveInstrument:c=!1,shouldSetAsDefaultInstrument:l=!1}=Bd(t)?t:{},u=d?yield this.get3DSNonce(s):s;return yield this.createOrder(u),{methodId:e,paymentData:Object.assign(Object.assign({},t),{shouldSaveInstrument:c,shouldSetAsDefaultInstrument:l,formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:u}}})}})}createOrder(e){return gc(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getCartOrThrow().id;if(this.methodId){const{orderId:n}=yield this.bigCommercePaymentsRequestSender.createOrder(this.methodId,{cartId:t,fastlaneToken:e});this.orderId=n}})}get3DSNonce(e){var t;return gc(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getCartOrThrow(),r=n.getOrderOrThrow(),o=n.getStoreConfigOrThrow().links.checkoutLink,a=null===(t=this.paypalFastlaneSdk)||void 0===t?void 0:t.ThreeDomainSecureClient;if(!a)throw new mi;const s={amount:r.orderAmount.toFixed(2),currency:i.currency.code,nonce:e,threeDSRequested:this.threeDSVerificationMethod===Ar.Always,transactionContext:{experience_context:{locale:"en-US",return_url:o,cancel_url:o}}},d=yield a.isEligible(s);if(this.threeDSVerificationMethod===Ar.Always&&!d)throw new Xr;if(d){const{liabilityShift:e,authenticationState:t,nonce:n}=yield a.show();if(e===ir.No||e===ir.Unknown||t===Tr.Errored||t===Tr.Cancelled)throw new Xr;if(t===Tr.Succeeded&&[ir.Yes,ir.Possible].includes(e))return n}return e})}handlePayPalStoredInstrumentChange(e){return gc(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:n,selectedCard:i}=yield t.profile.showCardSelector();if(n){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),n=yc(t)?t:{},r=this.bigCommercePaymentsFastlaneUtils.mapPayPalToBcInstrument(e,i)[0];return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},n),{instruments:[r]})),r}})}isBigcommercePaymentsFastlaneThreeDSAvailable(){return Ci(this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.bcp_fastlane_three_ds")}handleError(e){var t;(null===(t=this.bigcommerce_payments_fastlane)||void 0===t?void 0:t.onError)&&"function"==typeof this.bigcommerce_payments_fastlane.onError&&this.bigcommerce_payments_fastlane.onError(e)}}const vc=fi(e=>{const{getHost:t}=e.getState();return new fc(e,new fr(n({host:t()})),Rr(),Br())},[{id:"bigcommerce_payments_fastlane"}]);var _c=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Sc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.paypalSdkHelper=i}initialize(e){return _c(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_paylater:n}=e||{};if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:o=[],orderId:a}=r.initializationData||{},{bannerContainerId:s,container:d}=n;if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=o&&o.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.paypalSdkHelper.getPayPalMessages(r,i.getCartOrThrow().currency.code);return this.renderMessages(t,s,e)}a?this.orderId=a:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==d?void 0:d.split("#")[1],this.renderButton(t,n))})}execute(e,t){return _c(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);if(!this.orderId)throw new Xr;yield this.paymentIntegrationService.submitOrder(i,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(n.methodId,this.orderId)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.bigCommercePaymentsButtons)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){if(!(null==t?void 0:t.container))throw new vi('Unable to initialize payment because "container" argument is not provided.');const n=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=i.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u=[n.FUNDING.PAYLATER,n.FUNDING.CREDIT];let h=!1;u.forEach(e=>{if(h)return;const t={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.bigCommercePaymentsButtons=n.Buttons(t),this.bigCommercePaymentsButtons.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.bigCommercePaymentsButtons.isEligible()&&e===n.FUNDING.CREDIT)throw new _i(`BigCommercePayments ${e} is not available for your region. Please use BigCommercePayments Checkout instead.`);d&&"function"==typeof d&&d(),this.bigCommercePaymentsButtons.render(a),h=!0}})}handleClick(e,t){return _c(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;t&&"function"==typeof t&&(yield t(()=>(this.toggleLoadingIndicator(!0),n()),i))})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:lc(n)};e.Messages(i).render(`#${t}`)}}const Ic=fi(e=>new Sc(e,Sr(e),new fd({containerStyles:cc}),Rr()),[{id:"bigcommerce_payments_paylater"}]);class wc extends nr{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var Cc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class bc{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return Cc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_ratepay:i}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_ratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new vi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new vi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new vi("Unable to initialize payment because merchantId argument is not provided.");this.bigcommerce_payments_ratepay=i,yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return Cc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{getFieldsValues:r}=this.bigcommerce_payments_ratepay||{};if(!n)throw new co(["payment"]);if(!r||"function"!=typeof r)throw new vi('Unable to initialize payment because "options.getFieldsValues" argument is not provided.');this.toggleLoadingIndicator(!0);try{const e=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apmscheckout",{metadataId:this.guid}),{ratepayBirthDate:o,ratepayPhoneNumber:a,ratepayPhoneCountryCode:s}=r(),d={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:n.methodId,rate_pay:{birth_date:this.normalizeDate(o),phone:{national_number:a,country_code:s.split("+")[1]}},paypal_account:{order_id:e}}};return yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:d}),yield new Promise((e,t)=>{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.bigcommerce_payments_ratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new vi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.bigcommerce_payments_ratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return Cc(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return Cc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus("bigcommerce_payments_apms",{params:{useMetadata:!0}}),o=r===cr.PollingStop,a=r===cr.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,n,i);yield this.reinitializeStrategy({methodId:e,gatewayId:i,bigcommerce_payments_ratepay:this.bigcommerce_payments_ratepay}),this.handleError(new wc)}catch(e){this.handleError(e),n()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const Pc=fi(e=>new bc(e,Sr(e),new fd({containerStyles:Object.assign(Object.assign({},cc),{position:"fixed"})})),[{gateway:"bigcommerce_payments_apms",id:"ratepay"}]);var Oc;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification",e.CardExpiryVerification="cardExpiryVerification"}(Oc||(Oc={}));const Ec=Oc;function Ac(e){return Ec.CardNumber in e&&Ec.CardName in e&&Ec.CardExpiry in e}function Tc(e){return Ec.CardNumberVerification in e&&Ec.CardCodeVerification in e&&Ec.CardExpiryVerification in e}var kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Dc{constructor(e,t,n,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdk=n,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){return kc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_creditcards:n}=e,i=n,{form:r,onCreditCardFieldsRenderingError:o,onLoadComplete:a}=i||{};if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new vi('Unable to proceed because "options.bigcommerce_payments_creditcards.form" argument is not provided.');this.hostedFormOptions=r,this.isCreditCardForm=Ac(r.fields),this.isCreditCardVaultedForm=Tc(r.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(r,o)),null==a||a(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return kc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{methodId:r,paymentData:o}=n||{};if(!n||!r)throw new co(["payment"]);if(this.executionPaymentData=o,this.isCreditCardForm||this.isCreditCardVaultedForm)yield this.validateHostedFormOrThrow(),yield this.submitHostedForm();else{const{orderId:e}=yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",this.getInstrumentParams());this.returnedOrderId=e}const a=this.preparePaymentPayload(r,o,this.returnedOrderId,this.returnedVaultedToken);yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e,t,n,i;return kc(this,void 0,void 0,function*(){return yield null===(e=this.cvvField)||void 0===e?void 0:e.close(),yield null===(t=this.expiryField)||void 0===t?void 0:t.close(),yield null===(n=this.numberField)||void 0===n?void 0:n.close(),yield null===(i=this.nameField)||void 0===i?void 0:i.close(),Promise.resolve()})}preparePaymentPayload(e,t,n,i){const{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=Bd(t)?t:{},a=t&&Nd(t)?t.instrumentId:void 0,s=ue({verification_nonce:i,token:a},J);return{methodId:e,paymentData:{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o,instrumentId:a,formattedPayload:Object.assign(Object.assign({},i||a?{bigpay_token:s}:{}),n?{card_with_order:{order_id:n}}:{})}}}initializeFields(e,t){return kc(this,void 0,void 0,function*(){const{fields:n,styles:i}=e,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),o=this.getExecuteCallback(n),a=Object.assign({style:this.getInputStyles(i),onApprove:({orderID:e,vaultSetupToken:t,liabilityShift:n})=>{if(n===ir.No||n===ir.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ti.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>kc(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>kc(this,void 0,void 0,function*(){const{orderId:e}=(yield this.bigCommercePaymentsIntegrationService.createOrderCardFields("bigcommerce_payments_creditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return kc(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return kc(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(Bd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(Nd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return kc(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return kc(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ti.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isBigCommercePaymentsAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return kc(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(i,n.currency.code,n.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const Mc=fi(e=>new Dc(e,Sr(e),Rr(),Br()),[{id:"bigcommerce_payments_creditcards"}]);var zc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class xc{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdkHelper=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return zc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n,t),{orderId:a,shouldRenderFields:s}=o.initializationData||{},d=r.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=Ci(d,"PAYPAL-5624.bcp_ideal_polling"),a?this.orderId=a:(this.paypalApms=yield this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(o,r.getCartOrThrow().currency.code),this.loadingIndicatorContainer=i.container.split("#")[1],this.renderButton(n,t,i),s&&this.renderFields(n,i))})}execute(e,t){return zc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{methodId:r,gatewayId:o}=n;if(!this.orderId)throw new Xr;this.isPollingEnabled&&"ideal"===r&&(yield new Promise((e,t)=>{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.bigCommercePaymentsIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isPollingEnabled&&this.resetPollingMechanism(),null===(e=this.bigCommercePaymentsButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return zc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus(i),o=r===cr.Approved,a=r===cr.PollingError;if(o)return this.deInitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,n,i);yield this.reinitializeStrategy({methodId:e,gatewayId:i,bigCommercePaymentsAlternativeMethods:this.bigCommercePaymentsAlternativeMethods}),this.handleError(new wc)}catch(e){n()}})}deInitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deInitializePollingMechanism()}reinitializeStrategy(e){return zc(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderButton(e,t,n){const i=this.getPaypalAmpsSdkOrThrow(),r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t),{buttonStyle:o}=r.initializationData||{},{container:a,onError:s,onRenderButton:d,submitForm:c}=n,l={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),onInit:(e,t)=>n.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deInitializePollingMechanism()},onError:e=>{this.deInitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>zc(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.bigCommercePaymentsButton=i.Buttons(l),this.bigCommercePaymentsButton.isEligible()&&(d&&"function"==typeof d&&d(),this.bigCommercePaymentsButton.render(a))}onCreateOrder(e,t,n){return zc(this,void 0,void 0,function*(){const{onValidate:i}=n;yield i(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const r=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms");if(this.isNonInstantPaymentMethod(e)){const n={useStoreCredit:!1},i={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(n,i),yield this.bigCommercePaymentsIntegrationService.submitPayment(e,r,t)}return r})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_apms" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in dr}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const Nc=fi(e=>new xc(e,Sr(e),Rr(),new fd({containerStyles:cc})),[{gateway:"bigcommerce_payments_apms"}]);class Rc{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){const{gatewayId:t,methodId:n,bigcommerce_payments_apms:i}=e;if(this.bigCommercePaymentsAlternativeMethods=i,!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{methodId:r,gatewayId:o}=n;try{const e={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:r,paypal_account:{order_id:yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms",{gatewayId:"bigcommerce_payments_apms",methodId:r})}}};yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment({methodId:r,gatewayId:o,paymentData:e})}catch(e){if(function(e){var t,n;return pa(e)&&(null===(n=null===(t=e.body)||void 0===t?void 0:t.additional_action_required)||void 0===n?void 0:n.data.redirect_url)}(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise((e,n)=>{window.location.replace(t),n()})}return this.handleError(e),Promise.reject(e)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};t&&"function"==typeof t&&t(e)}}const Fc=fi(e=>new Rc(e,Sr(e)),[{gateway:"bigcommerce_payments_apms",id:"klarna"},{gateway:"bigcommerce_payments_apms",id:"afterpay"}]);var Lc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class jc{constructor(e,t,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return Lc(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_venmo:r}=e||{};if(!i)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=o.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=o.initializationData)||void 0===n?void 0:n.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=r.container.split("#")[1],this.renderButton(i,r))})}execute(e,t){return Lc(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);if(!this.orderId)throw new Xr;yield this.paymentIntegrationService.submitOrder(i,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(n.methodId,this.orderId)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){const n=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=i.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u={fundingSource:n.FUNDING.VENMO,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new _i("Venmo is not available for your region. Please another payment method instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return Lc(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;yield t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const Bc=fi(e=>new jc(e,Sr(e),new fd({styles:{backgroundColor:"black"}})),[{id:"bigcommerce_payments_venmo"}]);class Uc{initialize(e){this._blueSnapSdk=e}initialize3ds(e,t){return n=this,i=void 0,o=function*(){const n=this._getBlueSnapSdk();return new Promise((i,r)=>{n.threeDsPaymentsSetup(e,e=>"1"===e.code?i(e.threeDSecure.threeDSecureReferenceId):r(new Qr)),n.threeDsPaymentsSubmitData(t)})},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ti.PaymentNotInitialized))}}function qc(e){return Ec.CardNumber in e}function Vc(e){return Ec.CardCodeVerification in e||Ec.CardNumberVerification in e}var Gc,Hc,Wc,$c,Yc,Kc=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Jc{constructor(e,t,n,i){this._scriptLoader=e,this._paymentIntegrationService=t,this._blueSnapDirectHostedForm=n,this._blueSnapDirect3ds=i}initialize(e){return Kc(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,creditCard:i}=e;if(!n||!i)throw new vi;const r=yield this._paymentIntegrationService.loadPaymentMethod(n,{params:{method:t,bigpayToken:i.bigpayToken}}),{config:{testMode:o,is3dsEnabled:a},clientToken:s}=r.getPaymentMethodOrThrow(t,n);this._blueSnapSdk=yield this._scriptLoader.load(o),this._paymentFieldsToken=s,this._shouldUseHostedFields=qc(i.form.fields)||Vc(i.form.fields)&&!!i.form.fields.cardNumberVerification,this._shouldUseHostedFields&&(this._blueSnapDirectHostedForm.initialize(this._blueSnapSdk,i.form.fields),yield this._blueSnapDirectHostedForm.attach(this._getPaymentFieldsToken(),i,a))})}execute(e){return Kc(this,void 0,void 0,function*(){if(!e.payment)throw new co(["payment"]);if(!this._blueSnapSdk)throw new co(["payment"]);const{paymentData:t}=e.payment,{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:i}=Bd(t)?t:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},r=this._getPaymentFieldsToken();let o;const{is3dsEnabled:a}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.payment.methodId,e.payment.gatewayId).config,s=this._shouldUseHostedFields?yield this._blueSnapDirectHostedForm.validate().submit(a?this._getBlueSnapDirectThreeDSecureData():void 0,!(Bd(t)&&Nd(t))):void 0;if(yield this._paymentIntegrationService.submitOrder(),Bd(t)&&Nd(t)&&this._paymentFieldsToken&&t.instrumentId){if(a){this._blueSnapDirect3ds.initialize(this._blueSnapSdk);const{last4:e,brand:n}=this._paymentIntegrationService.getState().getCardInstrumentOrThrow(t.instrumentId),i=Object.assign({last4Digits:e,ccType:n.toUpperCase()},this._getBlueSnapDirectThreeDSecureData());o=yield this._blueSnapDirect3ds.initialize3ds(this._paymentFieldsToken,i)}yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:Object.assign(Object.assign(Object.assign({instrumentId:t.instrumentId},this._shouldUseHostedFields?{nonce:r}:{}),o?{deviceSessionId:o}:{}),{shouldSetAsDefaultInstrument:!!i})}))}else yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e.payment),{paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify({pfToken:r,cardHolderName:s&&s.cardHolderName})},vault_payment_instrument:n,set_as_default_stored_instrument:i}}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._shouldUseHostedFields&&this._blueSnapDirectHostedForm.detach(),Promise.resolve()}_getBlueSnapDirectThreeDSecureData(){var e;const{getBillingAddress:t,getShippingAddress:n,getCustomer:i,getCheckoutOrThrow:r,getCartOrThrow:o}=this._paymentIntegrationService.getState(),a=t(),s=n(),d=(null===(e=i())||void 0===e?void 0:e.email)||(null==a?void 0:a.email),c=(null==a?void 0:a.phone)||(null==s?void 0:s.phone);return Object.assign(Object.assign(Object.assign(Object.assign({amount:r().outstandingBalance,currency:o().currency.code},d&&{email:d}),c&&{phone:c}),a&&{billingFirstName:a.firstName,billingLastName:a.lastName,billingCountry:a.countryCode,billingCity:a.city,billingAddress:`${a.address1} ${a.address2}`.trim(),billingZip:a.postalCode}),s&&{shippingFirstName:s.firstName,shippingLastName:s.lastName,shippingCountry:s.countryCode,shippingCity:s.city,shippingAddress:`${s.address1} ${s.address2}`.trim(),shippingZip:s.postalCode})}_getPaymentFieldsToken(){return ii(this._paymentFieldsToken,()=>new ni(ei.MissingPaymentToken))}}!function(e){e.AMEX="american-express",e.CHINA_UNION_PAY="unionpay",e.DINERS="diners-club",e.DISCOVER="discover",e.JCB="jcb",e.MASTERCARD="mastercard",e.UNKNOWN="unknown",e.VISA="visa"}(Gc||(Gc={})),function(e){e.ON_BLUR="onBlur",e.ON_SUBMIT="onSubmit"}(Hc||(Hc={})),function(e){e.EMPTY="empty",e.INVALID="invalid",e.THREE_DS_NOT_ENABLED="3D Secure is not enabled"}(Wc||(Wc={})),function(e){e.CC_NOT_SUPORTED="22013",e.ERROR_403="403",e.ERROR_404="404",e.ERROR_500="500",e.INVALID_OR_EMPTY="10",e.SESSION_EXPIRED="400",e.THREE_DS_AUTH_FAILED="14101",e.THREE_DS_CLIENT_ERROR="14103",e.THREE_DS_MISSING_FIELDS="14102",e.THREE_DS_NOT_ENABLED="14100",e.TOKEN_EXPIRED="14040",e.TOKEN_NOT_ASSOCIATED="14042",e.TOKEN_NOT_FOUND="14041"}($c||($c={})),function(e){e.CardCode="cvv",e.CardExpiry="exp",e.CardName="noc",e.CardNumber="ccn"}(Yc||(Yc={}));const Zc={[Yc.CardNumber]:Ec.CardNumber,[Yc.CardExpiry]:Ec.CardExpiry,[Yc.CardName]:Ec.CardName,[Yc.CardCode]:Ec.CardCode},Qc={empty:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date is required",type:"required"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV is required",type:"required"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}},invalid:{[Ec.CardNumber]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[Ec.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date must be a valid future date in MM / YY format",type:"invalid_card_expiry"},[Ec.CardCode]:{fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},[Ec.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}}};class Xc{constructor(e,t){this._nameOnCardInput=e,this._hostedInputValidator=t}initialize(e,t){this._blueSnapSdk=e,t&&(qc(t)?this._hostedInputValidator.initialize():Vc(t)&&t.cardNumberVerification&&this._hostedInputValidator.initializeValidationFields())}attach(e,t,n){var i,r,o,a,s=t.form,{fields:d}=s,c=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(s,["fields"]);return void 0===n&&(n=!1),i=this,r=void 0,a=function*(){const t=this._getBlueSnapSdk();if(!qc(d)&&!Vc(d))throw new vi("Field options must be of type HostedCardFieldOptionsMap");return this._onValidate=c.onValidate,qc(d)&&this._setCustomBlueSnapAttributes(d),Vc(d)&&this._setCustomStoredCardsBlueSnapAttributes(d),new Promise(i=>{const r=this._getHostedPaymentFieldsOptions(e,d,c,i,n);t.hostedPaymentFieldsCreate(r),qc(d)&&this._nameOnCardInput.attach(r,d.cardName.accessibilityLabel,d.cardName.placeholder)})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}validate(){var e;const t=this._hostedInputValidator.validate();if(null===(e=this._onValidate)||void 0===e||e.call(this,t),!t.isValid){const e=Object.entries(t.errors).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n.map(({message:e,type:t})=>({message:e,type:t}))}),{});throw new lo(e)}return this}submit(e,t=!1){return new Promise((n,i)=>this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(e=>this._isBlueSnapDirectCallbackError(e)?i(new Qr(e.statusCode===$c.THREE_DS_AUTH_FAILED?e.error[0].errorDescription:`Submission failed with status: ${e.statusCode} and errors: ${JSON.stringify(e.error)}`)):n(Object.assign(Object.assign({},e.cardData),t?{cardHolderName:this._nameOnCardInput.getValue()}:{})),e))}detach(){this._nameOnCardInput.detach()}_isBlueSnapDirectCallbackError(e){return"error"in e}_getHostedPaymentFieldsOptions(e,t,{onFocus:n,onBlur:i,onValidate:r,onCardTypeChange:o,onEnter:a,styles:s},d,c){var l;return Object.assign(Object.assign(Object.assign({token:e,onFieldEventHandler:{setupComplete:()=>d(),onFocus:this._usetUiEventCallback(n),onBlur:this._usetUiEventCallback(i),onError:this._handleError(r),onType:(e,t)=>null==o?void 0:o({cardType:Gc[t]}),onEnter:this._usetUiEventCallback(a),onValid:e=>null==r?void 0:r(this._hostedInputValidator.validate({tagId:e}))}},qc(t)&&{ccnPlaceHolder:t.cardNumber.placeholder||"",cvvPlaceHolder:(null===(l=t.cardCode)||void 0===l?void 0:l.placeholder)||"",expPlaceHolder:t.cardExpiry.placeholder||"MM / YY"}),s&&{style:this._mapStyles(s)}),{"3DS":c})}_mapStyles({default:e,error:t,focus:n}){return Object.entries(Object.assign(Object.assign(Object.assign({},e&&{input:e}),t&&{".invalid":t}),n&&{":focus":n})).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:Object.entries(n).reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[te(t)]:n}),{})}),{})}_handleError(e){return(t,n,i,r)=>{if(n===$c.INVALID_OR_EMPTY&&t&&function(e){return void 0!==e&&[Wc.EMPTY,Wc.INVALID].includes(e)}(i))return null==e?void 0:e(this._hostedInputValidator.validate({tagId:t,errorDescription:i}));throw new Qr(`An unexpected error has occurred: ${JSON.stringify({tagId:t,errorCode:n,errorDescription:i,eventOrigin:r})}`)}}_usetUiEventCallback(e){return t=>{e&&e({fieldType:Zc[t]})}}_getBlueSnapSdk(){return ii(this._blueSnapSdk,()=>new ri(ti.PaymentNotInitialized))}_setCustomBlueSnapAttributes(e){const{cardNumber:t,cardExpiry:n,cardCode:i,cardName:r}=e,o=document.getElementById(t.containerId),a=document.getElementById(n.containerId),s=i&&document.getElementById(i.containerId),d=document.getElementById(r.containerId);if(!(o&&a&&s&&d))throw new vi("Unable to create hosted payment fields to invalid HTML container elements.");o.dataset.bluesnap=Yc.CardNumber,a.dataset.bluesnap=Yc.CardExpiry,s.dataset.bluesnap=Yc.CardCode,d.dataset.bluesnap=Yc.CardName}_setCustomStoredCardsBlueSnapAttributes(e){const{cardNumberVerification:t,cardCodeVerification:n}=e,i=t&&document.getElementById(t.containerId),r=n&&document.getElementById(n.containerId);(i||r)&&(i&&(i.dataset.bluesnap=Yc.CardNumber),r&&(r.dataset.bluesnap=Yc.CardCode))}}class el{constructor(){this._errors={}}initialize(){this._errors={cardNumber:[Qc.empty.cardNumber],cardExpiry:[Qc.empty.cardExpiry],cardCode:[Qc.empty.cardCode],cardName:[Qc.empty.cardName]}}initializeValidationFields(){this._errors={cardNumberVerification:[Qc.empty.cardNumber]}}validate(e){return e&&this._updateErrors(e.tagId,e.errorDescription),{isValid:Object.values(this._errors).every(e=>0===e.length),errors:this._errors}}_updateErrors(e,t){const n=this._errors.cardNumberVerification?Ec.CardNumberVerification:Zc[e];this._errors[n]=t?[Qc[t][n]]:[]}}class tl{attach({style:e,onFieldEventHandler:{onFocus:t,onBlur:n,onValid:i,onError:r,onEnter:o}={}},a,s){var d;this._style=e,this._create(),this._getInput().addEventListener("focus",this._handleFocus(t)),this._getInput().addEventListener("blur",this._handleBlur(n,i,r)),this._getInput().addEventListener("enter",this._handleEnter(o)),a&&this._getInput().setAttribute("aria-label",a),s&&(this._getInput().placeholder=s),null===(d=document.querySelector('[data-bluesnap="noc"]'))||void 0===d||d.appendChild(this._getInput())}getValue(){return this._getInput().value}detach(){this._input&&(this._input.remove(),this._input=void 0)}_handleFocus(e){return()=>{var t;this._applyStyles(null===(t=this._style)||void 0===t?void 0:t[":focus"]),null==e||e(Yc.CardName)}}_handleBlur(e,t,n){return({target:i})=>{var r,o;null==e||e(Yc.CardName),i instanceof HTMLInputElement&&(/\w{1,200}/.test(i.value)?(this._applyStyles(null===(r=this._style)||void 0===r?void 0:r.input),null==t||t(Yc.CardName)):(this._applyStyles(null===(o=this._style)||void 0===o?void 0:o[".invalid"]),null==n||n(Yc.CardName,$c.INVALID_OR_EMPTY,Wc.EMPTY,Hc.ON_BLUR)))}}_handleEnter(e){return()=>null==e?void 0:e(Yc.CardName)}_applyStyles(e={}){const t={color:e.color,fontFamily:e["font-family"],fontSize:e["font-size"],fontWeight:e["font-weight"]},n=Object.keys(t);n.every(e=>["color","fontFamily","fontSize","fontWeight"].includes(e))&&n.forEach(e=>{t[e]&&(this._getInput().style[e]=t[e]||"")})}_configureInput(){this._getInput().autocomplete="cc-name",this._getInput().id=Yc.CardName,this._getInput().inputMode="text",this._getInput().maxLength=200,this._getInput().style.backgroundColor="transparent",this._getInput().style.border="0",this._getInput().style.height="100%",this._getInput().style.margin="0",this._getInput().style.outline="none",this._getInput().style.padding="0",this._getInput().style.width="100%",this._getInput().type="text"}_getInput(){return ii(this._input,()=>new ri(ti.PaymentNotInitialized))}_create(){var e;this._input=document.createElement("input"),this._configureInput(),this._applyStyles(null===(e=this._style)||void 0===e?void 0:e.input)}}var nl;!function(e){e.PRODUCTION="https://pay.bluesnap.com/web-sdk/5/bluesnap.js",e.SANDBOX="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"}(nl||(nl={}));class il{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e=!1){return t=this,n=void 0,r=function*(){if(this._window.bluesnap)return this._window.bluesnap;if(yield this._scriptLoader.loadScript(e?nl.SANDBOX:nl.PRODUCTION),!this._window.bluesnap)throw new mi;return this._window.bluesnap},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const rl=fi(e=>new Jc(new il(a()),e,new Xc(new tl,new el),new Uc),[{id:"credit_card",gateway:"bluesnapdirect"}]);class ol{constructor(e){this._paymentIntegrationService=e}execute(e){return t=this,n=void 0,r=function*(){const t=this._formatePaymentPayload(e);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(t)}catch(e){if(this._isBlueSnapDirectRedirectResponse(e)){const t=e.body.provider_data&&JSON.parse(e.body.provider_data);let n=e.body.additional_action_required.data.redirect_url;if(function(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!t.merchantid&&"string"==typeof t.merchantid}(t)){const e=new URLSearchParams(t).toString();n=`${n}&${e}`}return new Promise(()=>window.location.replace(n))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_formatePaymentPayload({payment:e}){if(!e)throw new co(["payment"]);return e.paymentData&&Nd(e.paymentData)&&Bd(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{instrumentId:e.paymentData.instrumentId,shouldSetAsDefaultInstrument:!!e.paymentData.shouldSetAsDefaultInstrument}}):(t=e.paymentData,Boolean("object"==typeof t&&null!==t&&"accountNumber"in t&&"accountType"in t&&"shopperPermission"in t&&"routingNumber"in t)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ecp:Object.assign({account_number:e.paymentData.accountNumber,account_type:e.paymentData.accountType,shopper_permission:e.paymentData.shopperPermission,routing_number:e.paymentData.routingNumber},e.paymentData.companyName?{company_name:e.paymentData.companyName}:{}),vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):(n=e.paymentData,Boolean("object"==typeof n&&null!==n&&"iban"in n&&"firstName"in n&&"lastName"in n&&"shopperPermission"in n)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{sepa_direct_debit:{iban:e.paymentData.iban,first_name:e.paymentData.firstName,last_name:e.paymentData.lastName,shopper_permission:e.paymentData.shopperPermission},vault_payment_instrument:e.paymentData.shouldSaveInstrument,set_as_default_stored_instrument:e.paymentData.shouldSetAsDefaultInstrument}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"bic"in e)}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{ideal:{bic:e.paymentData.bic}}}}):function(e){return Boolean("object"==typeof e&&null!==e&&"iban"in e&&!("firstName"in e)&&!("lastName"in e)&&!("shopperPermission"in e))}(e.paymentData)?Object.assign(Object.assign({},e),{paymentData:{formattedPayload:{pay_by_bank:{iban:e.paymentData.iban}}}}):{methodId:e.methodId}));var t,n}_isBlueSnapDirectRedirectResponse(e){var t;if("object"!=typeof e||null===e)return!1;const n=e;if(!n.body)return!1;const i=n.body;return"additional_action_required"===i.status&&!!(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}}const al=fi(e=>new ol(e),[{gateway:"bluesnapdirect"}]);var sl;!function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(sl||(sl={}));const dl=sl;var cl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class ll{constructor(e){this._paymentIntegrationService=e}execute(e,t){return cl(this,void 0,void 0,function*(){const{payment:n}=e;if(!n)throw new co(["payment"]);if(!this._initializeOptions)throw new ri(ti.PaymentNotInitialized);const{onLoad:i,style:r}=this._initializeOptions,o=this._createIframe("bluesnapv2_hosted_payment_page",r),a=new An(new Promise(ce));i(o,()=>a.cancel(new Wi)),yield this._paymentIntegrationService.submitOrder(e,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:n.methodId,gatewayId:n.gatewayId,shouldSaveInstrument:!1,target:o.name,promise:a.promise})})}finalize(e){return cl(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),n=t.getOrder(),i=t.getPaymentStatus();if(!n||i!==dl.ACKNOWLEDGE&&i!==dl.FINALIZE)return Promise.reject(new Cd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(e){return cl(this,void 0,void 0,function*(){this._initializeOptions=e&&e.bluesnapv2,yield Promise.resolve()})}deinitialize(){return Promise.resolve()}_createIframe(e,t){const n=document.createElement("iframe");if(n.setAttribute("sandbox","allow-top-navigation allow-scripts allow-forms allow-same-origin"),n.name=e,t){const{border:e,height:i,width:r}=t;n.style.border=null!=e?e:"",n.style.height=null!=i?i:"",n.style.width=null!=r?r:""}return n}}const ul=fi(e=>new ll(e),[{gateway:"bluesnapv2"}]);class hl{constructor(e){this.storage=e}saveExtraItemsData(e,t){const n=[...t.physicalItems,...t.digitalItems].reduce((e,t)=>(e[t.productId]={brand:t.brand?t.brand:"",category:t.categoryNames?t.categoryNames.join(", "):""},e),{});try{return this.storage.setItem(this.getStorageKey(e),JSON.stringify(n)),n}catch(e){return{}}}readExtraItemsData(e){try{const t=this.storage.getItem(this.getStorageKey(e));if(!t)return null;const n=JSON.parse(t);return function(e){if(!Z(e))return!1;const t=Object.values(e).some(e=>!Z(e)||!("brand"in e)||!("category"in e));return Boolean(!t)}(n)?n:null}catch(e){return null}}clearExtraItemData(e){try{this.storage.removeItem(this.getStorageKey(e))}catch(e){}}getStorageKey(e){return e?`ORDER_ITEMS_${e}`:""}}function pl(e){return Boolean(e.hasOwnProperty("analytics"))}function ml(e){return"object"==typeof e&&null!==e&&"shouldCreateAccount"in e}class yl extends Xn{constructor(e){super(),this.errorCode=e,this.name="BoltPaymentsFieldError",this.type="bolt_payments_field_error",this.body={errors:[yl.getError(e)]}}static getError(e){switch(e){case"1000":case"2000":case"3000":return{code:"invalid_number"};case"1001":case"2001":case"3001":return{code:"invalid_expiry_date"};case"1002":case"2002":return{code:"invalid_cvc"};case"1003":return{code:"invalid_zip"};case"2003":return{code:"incorrect_zip"};default:return{code:"general_error"}}}}var gl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fl{constructor(e,t,n){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.analyticsExtraItemsManager=n,this.useBoltClient=!1,this.useBoltEmbedded=!1}initialize(e){return gl(this,void 0,void 0,function*(){const{bolt:t,methodId:n}=e,{containerId:i,onPaymentSelect:r,useBigCommerceCheckout:o}=t||{};if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)return void(this.boltClient=yield this.boltScriptLoader.loadBoltClient());const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l,embeddedOneClickEnabled:u}=s||{},{testMode:h}=d;if(!c)throw new ni(ei.MissingPaymentMethod);if(this.boltClient=yield this.boltScriptLoader.loadBoltClient(c,h,l),this.useBoltClient=!u,this.useBoltEmbedded=!!u,this.useBoltEmbedded){if(!i)throw new vi('Unable to initialize payment because "options.bolt.containerId" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.bolt.onPaymentSelect" argument is not provided.');this.boltEmbedded=yield this.boltScriptLoader.loadBoltEmbedded(c,h,l),this.mountBoltEmbeddedField(i),r(yield this.hasBoltAccount())}})}deinitialize(){var e;return null===(e=this.embeddedField)||void 0===e||e.unmount(),this.boltClient=void 0,this.boltEmbedded=void 0,Promise.resolve()}finalize(){return Promise.reject(new Cd)}execute(e,t){return gl(this,void 0,void 0,function*(){this.setExtraItemsForAnalytics();const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{methodId:r,paymentData:o}=n||{};let a;if(!e.payment)throw new co(["payment"]);if(!r)throw new ni(ei.MissingPaymentMethod);if(!o||!function(e){return Boolean(Z(e)&&("shouldSaveInstrument"in e||"nonce"in e||ml(e)))}(o))throw new ni(ei.MissingPayment);yield this.paymentIntegrationService.submitOrder(i,t),a=this.useBoltClient?yield this.getBoltClientPaymentPayload(r,o,t):this.useBoltEmbedded?yield this.getBoltEmbeddedPaymentPayload(r,o):yield this.getBoltFullCheckoutPaymentPayload(r,o),yield this.paymentIntegrationService.submitPayment(a)})}getBoltClientPaymentPayload(e,t,n){return gl(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e,n);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e).clientToken,{isStoreCreditApplied:o}=i.getCheckoutOrThrow(),{shouldSaveInstrument:a}=t,s=this.getBoltClientOrThrow();if(yield this.paymentIntegrationService.applyStoreCredit(o),!r)throw new ni(ei.MissingPaymentMethod);const d=yield new Promise((e,t)=>{const n={success:(n,i)=>{n.reference?e(n):t(new Qr("Unable to proceed because transaction reference is unavailable. Please try again later.")),i()},close:()=>{t(new Wi)}};s.configure({orderToken:r},{},n).open()});return{methodId:e,paymentData:{nonce:d.reference,shouldSaveInstrument:a}}})}getBoltEmbeddedPaymentPayload(e,t){var n;return gl(this,void 0,void 0,function*(){if(!ml(t))throw new ni(ei.MissingPayment);const i=this.validateTokenizeResultOrThrow(yield null===(n=this.embeddedField)||void 0===n?void 0:n.tokenize());return{methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:i.token,last_four_digits:i.last4,iin:i.bin,expiration_month:+i.expiration.split("-")[1],expiration_year:+i.expiration.split("-")[0]},provider_data:{create_account:!!t.shouldCreateAccount,embedded_checkout:!0}}}}})}getBoltFullCheckoutPaymentPayload(e,t){return gl(this,void 0,void 0,function*(){yield this.setBoltOrderId();const n=this.getBoltClientOrThrow(),i=yield n.getTransactionReference();if(!i)throw new Xr;return{methodId:e,paymentData:Object.assign(Object.assign({},t),{nonce:i})}})}getBoltClientOrThrow(){if(!this.boltClient)throw new ri(ti.PaymentNotInitialized);return this.boltClient}getBoltEmbeddedOrThrow(){if(!this.boltEmbedded)throw new ri(ti.PaymentNotInitialized);return this.boltEmbedded}hasBoltAccount(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress(),i=(null==t?void 0:t.email)||(null==n?void 0:n.email)||"",r=this.getBoltClientOrThrow();try{return yield r.hasBoltAccount(i)}catch(e){throw new Xr}})}setBoltOrderId(){return gl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getOrderOrThrow(),t=this.getBoltClientOrThrow();try{yield t.setOrderId(e.orderId)}catch(e){throw new Xr}})}mountBoltEmbeddedField(e){const t=this.getBoltEmbeddedOrThrow().create("payment_field",{styles:{backgroundColor:"#fff"},renderSeparateFields:!0});t.mount(`#${e}`),this.embeddedField=t}validateTokenizeResultOrThrow(e){if(!e)throw new Xr;if(e instanceof Error)throw new yl(e.message);const{token:t,last4:n,bin:i,expiration:r}=e,o=+n,a=+i,s=+`${r}`.split("-")[1],d=+`${r}`.split("-")[0];if(!t||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(s)||Number.isNaN(d))throw new co;return e}setExtraItemsForAnalytics(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfigOrThrow(),n=e.getCartOrThrow();if(t.checkoutSettings.isAnalyticsEnabled&&pl(window)){const{id:e,lineItems:t}=n;this.analyticsExtraItemsManager.saveExtraItemsData(e,t)}}}const vl=fi(e=>new fl(e,new ao(a()),new hl(Te)),[{id:"bolt"}]);function _l(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var Sl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Il{constructor(e,t){this.paymentIntegrationService=e,this.braintreeSdk=t}initialize(e){return Sl(this,void 0,void 0,function*(){const{methodId:t,braintreeach:n}=e||{};if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');this.getMandateText=null==n?void 0:n.getMandateText,yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{clientToken:r,initializationData:o}=i;if(!r||!o)throw new ni(ei.MissingPaymentMethod);this.braintreeSdk.initialize(r);try{this.usBankAccount=yield this.braintreeSdk.getUsBankAccount()}catch(e){this.handleBraintreeError(e)}})}execute(e,t){return Sl(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const r=Nd(n.paymentData||{}),o=r?yield this.tokenizePaymentForVaultedInstrument(n):yield this.tokenizePayment(n),a=r?yield this.preparePaymentDataForVaultedInstrument(o,n):yield this.preparePaymentData(o,n);yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Sl(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}tokenizePayment({paymentData:e}){return Sl(this,void 0,void 0,function*(){const t=this.getUsBankAccountOrThrow();if(!_l(e))throw new co(["payment.paymentData"]);const n=Nd(e)?"The data are used for stored instrument verification":"function"==typeof this.getMandateText&&this.getMandateText();if(!n)throw new vi("Unable to proceed because getMandateText is not provided or returned undefined value.");try{const{nonce:i}=yield t.tokenize({bankDetails:this.getBankDetails(e),mandateText:n});return i}catch(e){this.handleBraintreeError(e)}})}tokenizePaymentForVaultedInstrument(e){return Sl(this,void 0,void 0,function*(){const{methodId:t,paymentData:n={}}=e,i=this.paymentIntegrationService.getState(),{config:r}=i.getPaymentMethodOrThrow(t);if(!r.isVaultingEnabled)throw new vi("Vaulting is disabled but a vaulted instrument was being used for this transaction");return _l(n)?this.tokenizePayment(e):null})}preparePaymentData(e,t){return Sl(this,void 0,void 0,function*(){const{methodId:n,paymentData:i={}}=t;if(!_l(i))throw new co(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,routingNumber:s,accountNumber:d}=i;return{methodId:n,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 Sl(this,void 0,void 0,function*(){const{methodId:n,paymentData:i={}}=t;if(!Nd(i)||!Bd(i))throw new co(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{instrumentId:o,shouldSetAsDefaultInstrument:a}=i;return{methodId:n,paymentData:Object.assign({deviceSessionId:r,instrumentId:o,shouldSetAsDefaultInstrument:a},e&&{nonce:e})}})}getBankDetails(e){const t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n=e.ownershipType.toLowerCase(),i=e.accountType.toLowerCase();return Object.assign(Object.assign({accountNumber:e.accountNumber,routingNumber:e.routingNumber,ownershipType:n},"personal"===n?{firstName:e.firstName,lastName:e.lastName}:{businessName:e.businessName}),{accountType:i,billingAddress:{streetAddress:t.address1,extendedAddress:t.address2,locality:t.city,region:t.stateOrProvinceCode,postalCode:t.postalCode}})}getUsBankAccountOrThrow(){if(!this.usBankAccount)throw new ri(ti.PaymentNotInitialized);return this.usBankAccount}handleBraintreeError(e){if(!Ri(e))throw e;throw new Qr(e.message)}}const wl=fi(e=>new Il(e,(e=>{const t=new Ei(e),n=new Hi(a(),window,t);return new Ui(n)})(e)),[{id:"braintreeach"}]);class Cl{constructor(e){this.paymentIntegrationService=e,this.braintreeHostWindow=window}render(e,t,n){const i=t&&document.getElementById(t);if(this.braintreeHostWindow.paypal&&i){const r=this.paymentIntegrationService.getState(),o=r.getCartOrThrow(),a=r.getBillingAddressOrThrow(),s=r.getPaymentMethodOrThrow(e);if(!s.initializationData)return;const{paypalBNPLConfiguration:d=[]}=s.initializationData,c=n===vo.PAYMENT?"checkout":n,l=d&&d.find(({id:e})=>e===c);if(!l||!l.status)return;n===vo.CART&&(i.removeAttribute("data-pp-style-logo-type"),i.removeAttribute("data-pp-style-logo-position"),i.removeAttribute("data-pp-style-text-color"),i.removeAttribute("data-pp-style-text-size")),this.braintreeHostWindow.paypal.Messages({amount:o.cartAmount,buyerCountry:a.countryCode,placement:n,style:this.getPaypalMessagesStylesFromBNPLConfig(l)}).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 bl{constructor(e){const{element:t,closeElement:n,mainElement:i}=this._createElements(e);this._element=t,this._closeElement=n,this._mainElement=i}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:n="rgba(0, 0, 0, 0.8)",id:i="checkoutOverlay",transitionDuration:r=400,hasCloseButton:o=!1,innerHtml:a=null}=e||{};let s,d,c,l,u=t;if(i&&(t.id=i),a){const e=document.createElement("div");l=`${i}--overlayText`,e.className=l,e.appendChild(a),t.appendChild(e)}return o&&(c=`${i}--close`,s=document.createElement("div"),s.className=c,d=`${i}--layout`,u=document.createElement("div"),u.className=d,u.appendChild(t),u.appendChild(s)),u.appendChild(function(e){const{id:t,background:n,transitionDuration:i,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 ${i}ms ease-out;\n background: ${n};\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:i,background:n,transitionDuration:r,classLayout:d,classOverlayText:l,classClose:c})),{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:n}=e;this._addEventListener(this._element,t),this._addEventListener(this._closeElement,n),this._unregisterClick=()=>{this._removeEventListener(this._element,t),this._removeEventListener(this._closeElement,n),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 Pl={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};function Ol(e){return"object"==typeof e&&null!==e&&"name"in e&&"BraintreeError"===e.name}function El(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 Al=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Tl{constructor(e,t,n,i){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeMessages=n,this.loadingIndicator=i,this.braintreeHostWindow=window}initialize(e){return Al(this,void 0,void 0,function*(){const{braintree:t,methodId:n}=e;if(this.braintree=t,this.paymentMethod&&this.paymentMethod.nonce||(this.paymentMethod=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n)),this.paymentMethod.clientToken&&(null==t?void 0:t.bannerContainerId))return yield this.loadPaypal(),this.loadPaypalCheckoutInstance();if(this.paymentMethod.clientToken)return this.loadPaypal();const i=yield this.paymentIntegrationService.loadPaymentMethod(n);if(this.paymentMethod=i.getPaymentMethodOrThrow(n),null==t?void 0:t.bannerContainerId)return this.loadPaypalCheckoutInstance();if(!this.paymentMethod.clientToken)throw new ni(ei.MissingPaymentMethod);return this.loadPaypal()})}execute(e,t){var n;return Al(this,void 0,void 0,function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{onError:o}=this.braintree||{};if(!i)throw new co(["payment"]);try{const e=yield this.preparePaymentData(i,r.useStoreCredit);yield this.paymentIntegrationService.submitOrder(r,t),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.isProviderError(e)&&(yield this.loadPaypal(),null===(n=this.paypalButtonRender)||void 0===n||n.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 Cd)}deinitialize(){var e;return this.braintreeTokenizePayload=void 0,null===(e=this.paypalButtonRender)||void 0===e||e.close(),this.braintreeIntegrationService.teardown()}preparePaymentData(e,t){var n;return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getOutstandingBalance(t),o=i.getStoreConfig();if(!r)throw new ni(ei.MissingCheckout);if(!o)throw new ni(ei.MissingCheckoutConfig);if(!this.paymentMethod)throw new ri(ti.PaymentNotInitialized);const{currency:a,storeProfile:{storeLanguage:s}}=o,{nonce:d,config:{isVaultingEnabled:c}}=this.paymentMethod,{methodId:l,paymentData:u={}}=e,h=(null===(n=this.braintreeTokenizePayload)||void 0===n?void 0:n.nonce)||d;if(h){const t=yield this.paymentIntegrationService.loadPaymentMethod(l);return this.paymentMethod=t.getPaymentMethod(l),Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(h)})}if(Nd(u)||(p=u,Boolean(p.instrumentId)&&!Object.prototype.hasOwnProperty.call(p,"ccNumber")&&!Object.prototype.hasOwnProperty.call(p,"ccCvv"))){if(!c)throw new vi("Vaulting is disabled but a vaulted instrument was being used for this transaction");return Promise.resolve(e)}var p;if(!Bd(u))throw new ni(ei.MissingPayment);const{shouldSaveInstrument:m,shouldSetAsDefaultInstrument:y}=u;if(m&&!c)throw new vi("Vaulting is disabled but shouldSaveInstrument is set to true");const g=i.getShippingAddress(),f=g?El(g):void 0;return Promise.all([this.braintreeIntegrationService.paypal({amount:r,locale:s,currency:a.code,offerCredit:"braintreepaypalcredit"===this.paymentMethod.id,shippingAddressOverride:f,shouldSaveInstrument:m||!1,shippingAddressEditable:!1}),this.braintreeIntegrationService.getSessionId()]).then(([{nonce:t,details:n}={},i])=>Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(t,n&&n.email,i,m,y)}))})}formattedPayload(e,t,n,i,r){return{formattedPayload:{vault_payment_instrument:i||null,set_as_default_stored_instrument:r||null,device_info:n||null,paypal_account:{token:e,email:t||null}}}}loadPaypalCheckoutInstance(){return Al(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t,id:n}=this.paymentMethod||{};if(!e)throw new ni(ei.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e);const i={currency:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,intent:null==t?void 0:t.intent,isCreditEnabled:null==t?void 0:t.isCreditEnabled},r="braintreepaypalcredit"===n||!(null==t?void 0:t.isCreditEnabled);yield this.braintreeIntegrationService.getPaypalCheckout(i,e=>{var t;r&&n&&(null===(t=this.braintree)||void 0===t?void 0:t.bannerContainerId)&&this.renderPayPalMessages(n,this.braintree.bannerContainerId),this.renderPayPalButton(e)},this.handleError)}catch(e){this.handleError(e)}})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,vo.PAYMENT)}renderPayPalButton(e){const{onPaymentError:t,submitForm:n,onRenderButton:i,containerId:r,onError:o}=this.braintree||{};if(!r)return;const a=this.getSmartButtonContainerId(r);if(!document.getElementById(a))throw new vi(`Unable to initialize payment because element with id ${r} does not exist.`);if(!this.paymentMethod)throw new ri(ti.PaymentNotInitialized);this.loadingIndicatorContainer=r.split("#")[1];const{id:s,config:{testMode:d}}=this.paymentMethod,{paypal:c}=this.braintreeHostWindow,l=null==c?void 0:c.FUNDING.PAYPAL;c&&l?(this.paypalButtonRender=c.Buttons({env:d?"sandbox":"production",commit:!1,fundingSource:l,onClick:()=>{this.toggleLoadingIndicator(!0)},createOrder:()=>this.setupPayment(e,s,t),onApprove:t=>Al(this,void 0,void 0,function*(){this.braintreeTokenizePayload=yield this.tokenizePaymentOrThrow(t,e),n&&"function"==typeof n&&n()}),onCancel:()=>{this.toggleLoadingIndicator(!1)},onError:e=>{this.toggleLoadingIndicator(!1),null==o||o(e)}}),i&&"function"==typeof i&&i(),this.paypalButtonRender.isEligible()&&this.paypalButtonRender.render(`${r}`)):this.removeElement(r.split("#")[1])}setupPayment(e,t,n){return Al(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState();try{const n=i.getCustomer(),r=i.getPaymentMethodOrThrow(t),o=i.getCheckoutOrThrow().outstandingBalance,a=i.getStoreConfigOrThrow().currency.code,s=i.getShippingAddress()||(null==n?void 0:n.addresses[0]),d=s?El(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 n&&(Ol(e)||e instanceof Xn)&&n(e),e}})}tokenizePaymentOrThrow(e,t,n){return Al(this,void 0,void 0,function*(){try{return yield t.tokenizePayment(e)}catch(e){throw n&&(Ol(e)||e instanceof Xn)&&n(e),e}})}loadPaypal(){return Al(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t}=this.paymentMethod||{};if(!e||!t)throw new ni(ei.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e),yield this.braintreeIntegrationService.getPaypal()}catch(e){this.handleError(e)}return Promise.resolve()})}handleError(e){if(!Ol(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Wi(e.message);throw new Qr(e.message)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"2046"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.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()}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const kl=fi(e=>{const t=window,n=new bl,i=new Ei(e),r=new So(new Hi(a(),t,i),t,n),o=new Cl(e);return new Tl(e,r,o,new fd({containerStyles:Pl}))},[{id:"braintreepaypal"},{id:"braintreepaypalcredit"}]);class Dl{constructor(e){this.requestSender=e}getOrderStatus(e="braintreelocalmethods",t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/initialization/${e}`,i=Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr);return(yield this.requestSender.get(n,Object.assign({headers:i},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}var Ml=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class zl{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.braintreeSdk=t,this.braintreeRequestSender=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.isLPMsUpdateExperimentEnabled=!1,this.pollingTimer=0,this.stopPolling=ce,this.isPollingEnabled=!1}initialize(e){return Ml(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,braintreelocalmethods:i}=e;if(this.gatewayId=t,!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');this.braintreelocalmethods=i,this.loadingIndicatorContainer=i.container.split("#")[1],yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(t),{clientToken:a,config:s,initializationData:d}=o,c=r.getStoreConfigOrThrow().checkoutSettings.features;if(this.isPollingEnabled=Ci(c,"PAYPAL-5258.braintree_local_methods_polling"),this.isLPMsUpdateExperimentEnabled=Ci(c,"PAYPAL-4853.add_new_payment_flow_for_braintree_lpms"),!a||!d||!s.merchantId)throw new ni(ei.MissingPaymentMethod);try{this.braintreeSdk.initialize(a),this.isNonInstantPaymentMethod(n)||(this.braintreeLocalPayment=yield this.braintreeSdk.getBraintreeLocalPayment(s.merchantId))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Ml(this,void 0,void 0,function*(){return this.toggleLoadingIndicator(!1),Promise.resolve()})}execute(e,t){return Ml(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{methodId:r}=n;this.toggleLoadingIndicator(!0),this.isNonInstantPaymentMethod(r)?yield this.executeWithNotInstantLPM(r):yield this.executeWithInstantLPM(r,i,t)})}executeWithNotInstantLPM(e){return Ml(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,n)=>{window.location.replace(t),this.toggleLoadingIndicator(!1),n()})}return this.handleError(e),Promise.reject(e)}})}executeWithInstantLPM(e,t,n){return Ml(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment)throw new Xr;yield new Promise((i,r)=>{var o;null===(o=this.braintreeLocalPayment)||void 0===o||o.startPayment(this.getInstantLPMConfig(e,t,n),this.getInstantLPMCallback(i,r,e,t,n))})})}getLPMsBasicPaymentData(){return Ml(this,void 0,void 0,function*(){const{deviceData:e}=yield this.braintreeSdk.getDataCollectorOrThrow();return{deviceSessionId:e}})}getInstantLPMConfig(e,t,n){const i=this.paymentIntegrationService.getState(),r=i.getCartOrThrow(),o=i.getBillingAddressOrThrow(),{firstName:a,lastName:s,countryCode:d}=o,{currency:c,email:l,lineItems:u}=r,h=u.physicalItems.length>0,p=i.getCheckoutOrThrow().outstandingBalance,m=i.getStoreConfigOrThrow().links.checkoutLink;return{paymentType:e,amount:p,fallback:{url:m,buttonText:"Complete Payment"},currencyCode:c.code,shippingAddressRequired:h,email:l,givenName:a,surname:s,address:{countryCode:d},onPaymentStart:(i,r)=>Ml(this,void 0,void 0,function*(){if(!this.isLPMsUpdateExperimentEnabled)return this.orderId=i.paymentId,void r();const o=yield this.getLPMsBasicPaymentData(),a=Object.assign(Object.assign({},o),{formattedPayload:{method:e,[`${e}_account`]:{order_id:i.paymentId}}});try{yield this.paymentIntegrationService.submitOrder(t,n),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,n)=>{this.initializePollingMechanism(e,t,n,this.gatewayId)}):void 0;throw t}})}}getInstantLPMCallback(e,t,n,i,r){const o=this.paymentIntegrationService.getState().getCartOrThrow();return(a,s)=>Ml(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 Xr));const d=yield this.getLPMsBasicPaymentData(),c=Object.assign(Object.assign({},d),{formattedPayload:{method:n,[`${n}_account`]:Object.assign({email:o.email,token:s.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId})}});try{return this.isLPMsUpdateExperimentEnabled||(yield this.paymentIntegrationService.submitOrder(i,r)),yield this.paymentIntegrationService.submitPayment({methodId:n,paymentData:c}),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 Di}isBraintreeRedirectError(e){var t;if("object"!=typeof e||null===e)return!1;const{body:n}=e;return!!n&&!!(null===(t=n.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:n}=e;return!!n&&(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.hasOwnProperty("order_id_saved_successfully"))}initializePollingMechanism(e,t,n,i){return Ml(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.braintreeRequestSender.getOrderStatus(i,{params:{useMetadata:!1}}),o=r.status===ki.Pending,a=r.status===ki.Completed,s=r.status===ki.Failed;if(a)return this.deinitializePollingMechanism(),t();if(s)return n();if(!a&&o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,n,i);yield this.reinitializeStrategy({methodId:e,gatewayId:i,braintreelocalmethods:this.braintreelocalmethods}),this.handleError(new wc)}catch(e){n()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}reinitializeStrategy(e){return Ml(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}}const xl=fi(e=>{const t=window,i=new Ei(e),r=new Ui(new Hi(a(),t,i)),o=n(),s=new Dl(o);return new zl(e,r,s,new fd({styles:{backgroundColor:"black"}}))},[{gateway:"braintreelocalmethods"}]);function Nl(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var Rl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Fl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.braintreeSdk=n}initialize(e){var t;return Rl(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.braintreefastlane" argument is not provided.');if(!i.onInit||"function"!=typeof i.onInit)throw new vi('Unable to initialize payment because "options.braintreefastlane.onInit" argument is not provided or it is not a function.');if(!i.onChange||"function"!=typeof i.onChange)throw new vi('Unable to initialize payment because "options.braintreefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{initializationData:a,clientToken:s}=o||{},{isFastlaneStylingEnabled:d}=a||{},c=Ci(r.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");this.is3DSEnabled=o.config.is3dsEnabled,s&&c&&this.braintreeSdk.initialize(s);const l=Ao(d?null===(t=o.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,i.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(n,l),this.shouldRunAuthenticationFlow()&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow()),yield this.initializeCardComponent(),this.onError=i.onError,i.onInit(e=>this.renderBraintreeCardComponent(e)),i.onChange(()=>this.handleBraintreeStoredInstrumentChange(n))})}execute(e,t){return Rl(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);yield this.paymentIntegrationService.submitOrder(i,t);const r=yield this.preparePaymentPayload(n.methodId);yield this.paymentIntegrationService.submitPayment(r),this.braintreeFastlaneUtils.removeSessionIdFromCookies()})}finalize(){return Promise.reject(new Cd)}deinitialize(){return Rl(this,void 0,void 0,function*(){return this.braintreeCardComponent=void 0,Promise.resolve()})}initializeCardComponent(){return Rl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),{phone:t,firstName:n,lastName:i}=e.getBillingAddressOrThrow(),r=`${n} ${i}`,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 vi('Unable to initialize payment because "container" argument is not provided.');t.render(e)}preparePaymentPayload(e){var t,n;return Rl(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),r=i.getBillingAddressOrThrow(),o=`${r.firstName} ${r.lastName}`,a=this.getPayPalInstruments()[0],s=yield this.braintreeFastlaneUtils.getDeviceSessionId(),d=Ci(i.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:c}=this.getBraintreeCardComponentOrThrow(),l=yield c({name:{fullName:o},billingAddress:this.mapToPayPalAddress(r)}),u=(null===(n=null===(t=l.paymentSource.card)||void 0===t?void 0:t.binDetails)||void 0===n?void 0:n.bin)||"",h=this.is3DSEnabled&&d?yield this.get3DS(l.id,u):void 0;return{methodId:e,paymentData:{deviceSessionId:s,nonce:h||l.id}}})}get3DS(e,t){return Rl(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=yield this.braintreeSdk.getBraintreeThreeDS(),r=n.getOrderOrThrow();return new Promise((n,o)=>{i.verifyCard({amount:null==r?void 0:r.orderAmount,nonce:e,bin:t,onLookupComplete:(e,t)=>{i.on("customer-canceled",()=>{"function"==typeof this.onError&&this.onError(new Wi),o(new Wi)}),t()}},(e,t)=>(e&&"THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT"===e.code&&("function"==typeof this.onError&&this.onError(new Wi),o(new Wi)),n(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(),n=e.getCustomerOrThrow(),i=e.getPaymentProviderCustomer(),r=Nl(i)?i:{},o=this.braintreeFastlaneUtils.getSessionIdFromCookies();return!(!n.isGuest||(null==r?void 0:r.authenticationState)===Mi.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}getBraintreeCardComponentOrThrow(){if(!this.braintreeCardComponent)throw new mi;return this.braintreeCardComponent}getPayPalInstruments(){const e=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow();return(Nl(e)?e:{}).instruments||[]}handleBraintreeStoredInstrumentChange(e){return Rl(this,void 0,void 0,function*(){const t=this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow(),{selectionChanged:n,selectedCard:i}=yield t.profile.showCardSelector();if(n){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),n=Nl(t)?t:{},r=this.braintreeFastlaneUtils.mapPayPalToBcInstrument(e,[i]);if(r&&r.length>0)return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},n),{instruments:[...r]})),r[0]}})}}const Ll=fi(e=>{const t=window,n=new Ei(e),i=new So(new Hi(a(),t,n),t),r=new Mo(e,i),o=new Hi(a(),t,n),s=new Ui(o);return new Fl(e,r,s)},[{id:"braintreeacceleratedcheckout"}]);var jl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Bl{constructor(e,t,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=n}initialize(e){return jl(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:n}=e;if(!t)throw new vi('Unable to initialize payment because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState();this.paymentMethod=i.getPaymentMethodOrThrow(n);const r=i.getCheckoutOrThrow(),o=i.getStoreConfigOrThrow(),{clientToken:a,config:s}=this.paymentMethod||{};if(!a)throw new ni(ei.MissingPaymentMethod);const{onError:d=ce,onPaymentSelect:c=ce}=t;this.braintreeSdk.initialize(a);const l=yield this.braintreeSdk.getBraintreeVisaCheckout(),u=yield this.braintreeSdk.getVisaCheckoutSdk(null==s?void 0:s.testMode),h=l.createInitOptions({settings:{locale:o.storeProfile.storeLanguage,shipping:{collectShipping:!1}},paymentRequest:{currencyCode:o.currency.code,subtotal:String(r.subtotal)}});yield u.init(h),u.on("payment.success",e=>this.tokenizePayment(l,e).then(()=>Promise.all([this.paymentIntegrationService.loadCheckout(),this.paymentIntegrationService.loadPaymentMethod(n)])).then(()=>c()).catch(e=>d(e))),u.on("payment.error",(e,t)=>d(t))})}execute(e,t){var n,i;return jl(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!r)throw new vi('Unable to submit payment because "payload.payment" argument is not provided.');if(!(null===(i=null===(n=this.paymentMethod)||void 0===n?void 0:n.initializationData)||void 0===i?void 0:i.nonce))throw new ni(ei.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 Cd)}deinitialize(){return jl(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}tokenizePayment(e,t){return jl(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const n=this.paymentIntegrationService.getState(),i=n.getShippingAddress(),r=n.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(i),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:n,billingAddress:i,shippingAddress:r,details:o}=e,{userEmail:a}=n,{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,i)),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 Qr(e.message);throw e}}const Ul=fi(e=>{const t=window,n=new Ei(e),i=new Ui(new Hi(a(),t,n));return new Bl(e,Ee(),i)},[{id:"braintreevisacheckout"}]);var ql=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}initialize(e){return ql(this,void 0,void 0,function*(){const{methodId:t}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState();this.venmoOptions=e.braintreevenmo;const i=n.getPaymentMethodOrThrow(t);yield this.initializeBraintreeVenmo(i)})}execute(e){return ql(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!t)throw new co(["payment"]);try{const e=yield this.preparePaymentData(t);yield this.paymentIntegrationService.submitOrder(n),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return ql(this,void 0,void 0,function*(){return yield this.braintreeIntegrationService.teardown(),Promise.resolve()})}handleError(e){if(!Ri(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Wi(e.message);throw new Qr(e.message)}initializeBraintreeVenmo(e){var t;return ql(this,void 0,void 0,function*(){const{clientToken:n}=e;if(!n)throw new ni(ei.MissingPaymentMethod);const i=Ci(this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features,"PAYPAL-5406.braintree_venmo_web_fallback_support");try{this.braintreeIntegrationService.initialize(n),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}:{}),i?{mobileWebFallBack:i}:{}))}catch(e){this.handleError(e)}})}preparePaymentData(e){return ql(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{nonce:n}=t.getPaymentMethodOrThrow(e.methodId);if(n)return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(n)});const i=yield this.braintreeVenmoTokenize(),r=yield this.braintreeIntegrationService.getSessionId();return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(i.nonce,i.details.email,r)})})}formattedPayload(e,t,n){return{formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:n||null,paypal_account:{token:e,email:t||null}}}}braintreeVenmoTokenize(){return new Promise((e,t)=>{var n;null===(n=this.braintreeVenmoCheckout)||void 0===n||n.tokenize((n,i)=>{if(n)return t(n);e(i)})})}}const Gl=fi(e=>{const t=window,n=a(),i=new Ei(e),r=new Hi(n,t,i),o=new So(r,t);return new Vl(e,o)},[{id:"braintreevenmo"}]);var Hl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Wl{constructor(e,t,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeHostedForm=n}initialize(e){return Hl(this,void 0,void 0,function*(){const{methodId:t,gatewayId:n,braintree:i}=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 ni(ei.MissingPaymentMethod);this.threeDSecure=null==i?void 0:i.threeDSecure,this.onPaymentError=null==i?void 0:i.onPaymentError;try{this.braintreeIntegrationService.initialize(o,this.threeDSecure),this.isHostedPaymentFormEnabled(t,n)&&(null==i?void 0:i.form)&&(yield this.braintreeHostedForm.initialize(i.form,i.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 Hl(this,void 0,void 0,function*(){const{payment:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!t)throw new co(["payment"]);this.isHostedFormInitialized&&this.braintreeHostedForm.validate(),yield this.paymentIntegrationService.submitOrder(n);const i=this.paymentIntegrationService.getState(),r=i.getBillingAddressOrThrow(),o=i.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 Cd)}deinitialize(){return Hl(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 n;if(Ol(e)){if(!(t&&this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:t})||"HOSTED_FIELDS_INVALID_FIELD_SELECTOR"!==e.code))return;if(e.code.startsWith("THREEDS_"))return null===(n=this.onPaymentError)||void 0===n||n.call(this,new Qr("THREEDS_VERIFICATION_FAILED")),Promise.reject();throw new Qr(e.message)}throw e}preparePaymentData(e,t,n){return Hl(this,void 0,void 0,function*(){const{paymentData:i}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e))return Object.assign(Object.assign({},r),i);const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=Bd(i)?i:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.braintreeIntegrationService.verifyCard(e,t,n):yield this.braintreeIntegrationService.tokenizeCard(e,t);return Object.assign(Object.assign({},r),{nonce:s,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})})}prepareHostedPaymentData(e,t,n){return Hl(this,void 0,void 0,function*(){const{paymentData:i}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e)){const{nonce:e}=yield this.braintreeHostedForm.tokenizeForStoredCardVerification();return Object.assign(Object.assign(Object.assign({},r),i),{nonce:e})}const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=Bd(i)?i:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.verifyCardWithHostedForm(t,n):yield this.braintreeHostedForm.tokenize(t);return Object.assign(Object.assign({},r),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,nonce:s})})}prepareAdditionalActionPaymentData(e,t){const{paymentData:n}=e,i={deviceSessionId:this.deviceSessionId,nonce:t},{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=Bd(n)?n:{};return this.isSubmittingWithStoredCard(e)&&(r||o)?Object.assign(Object.assign({},n),i):Object.assign({},i)}verifyCardWithHostedForm(e,t){return Hl(this,void 0,void 0,function*(){const n=yield this.braintreeHostedForm.tokenize(e);return this.braintreeIntegrationService.challenge3DSVerification(n,t)})}processAdditionalAction(e,t,n){return Hl(this,void 0,void 0,function*(){if(!pa(e)||!fe(e.body.errors,{code:"three_d_secure_required"}))return this.handleError(e);try{const{payer_auth_request:i}=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||!Nd(r))throw new co(["instrumentId"]);const a=o.getCardInstrumentOrThrow(r.instrumentId),{nonce:s}=yield this.braintreeIntegrationService.challenge3DSVerification({nonce:i||"",bin:a.iin},n),d=this.prepareAdditionalActionPaymentData(t,s);yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},t),{paymentData:d}))}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||!Nd(e.paymentData))}shouldPerform3DSVerification(e){return!(!this.is3dsEnabled||this.isSubmittingWithStoredCard(e))}shouldInitializeBraintreeFastlane(){var e;const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),n=Nl(t)?t:{};return(null===(e=this.paymentMethod)||void 0===e?void 0:e.initializationData.isAcceleratedCheckoutEnabled)&&!(null==n?void 0:n.authenticationState)}initializeBraintreeFastlaneOrThrow(e){return Hl(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{clientToken:r,config:o}=i;if(!r)throw new ni(ei.MissingPaymentMethod);this.braintreeIntegrationService.initialize(r,this.threeDSecure),yield this.braintreeIntegrationService.getBraintreeFastlane(n.id,o.testMode)})}}function $l(e){return"cardNumber"in e}function Yl(e){if(!Ri(e))return!1;const{details:t}=e;return void 0===t||"object"==typeof t&&null!==t&&void 0===t.invalidFieldKeys||(n=t,Array.isArray(n)&&n.every(e=>"string"==typeof e));var n}var Kl,Jl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e[e.CreditCard=0]="CreditCard",e[e.StoredCardVerification=1]="StoredCardVerification"}(Kl||(Kl={}));class Zl{constructor(e,t){this.braintreeScriptLoader=e,this.braintreeSDKVersionManager=t,this.isInitializedHostedForm=!1,this.handleBlur=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onBlur)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy),errors:this.mapErrors(e.fields)})},this.handleFocus=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onFocus)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleCardTypeChange=e=>{var t,n;const i=1===e.cards.length?e.cards[0].type.replace(/^master-card$/,"mastercard"):void 0;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onCardTypeChange)||void 0===n||n.call(t,{cardType:i})},this.handleInputSubmitRequest=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onEnter)||void 0===n||n.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleValidityChange=e=>{var t,n;null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:this.isValidForm(e),errors:this.mapValidationErrors(e.fields)})}}initialize(e,t,n){var i,r,o,a,s;return Jl(this,void 0,void 0,function*(){this.clientToken=n,this.formOptions=e,this.type=$l(e.fields)?Kl.CreditCard:Kl.StoredCardVerification;const d=this.mapFieldOptions(e.fields,t);$(d)?this.isInitializedHostedForm=!1:(this.cardFields=yield this.createHostedFields({fields:d,styles:e.styles&&this.mapStyleOptions(e.styles)}),null===(i=this.cardFields)||void 0===i||i.on("blur",this.handleBlur),null===(r=this.cardFields)||void 0===r||r.on("focus",this.handleFocus),null===(o=this.cardFields)||void 0===o||o.on("cardTypeChange",this.handleCardTypeChange),null===(a=this.cardFields)||void 0===a||a.on("validityChange",this.handleValidityChange),null===(s=this.cardFields)||void 0===s||s.on("inputSubmitRequest",this.handleInputSubmitRequest),this.isInitializedHostedForm=!0)})}isInitialized(){return!!this.isInitializedHostedForm}deinitialize(){var e;return Jl(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 ri(ti.PaymentNotInitialized);const e=this.cardFields.getState();if(!this.isValidForm(e)){this.handleValidityChange(e);const t=this.mapValidationErrors(e.fields);throw new lo(t)}}tokenize(e){var t,n,i,r,o;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ti.PaymentNotInitialized);try{const r=yield this.cardFields.tokenize(ue({billingAddress:e&&this.mapBillingAddress(e)},J));return null===(n=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===n||n.call(t,{isValid:!0,errors:{}}),{nonce:r.nonce,bin:null===(i=r.details)||void 0===i?void 0:i.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e);if(t)throw null===(o=null===(r=this.formOptions)||void 0===r?void 0:r.onValidate)||void 0===o||o.call(r,{isValid:!1,errors:t}),new lo(t)}throw e}})}tokenizeForStoredCardVerification(){var e,t,n,i,r;return Jl(this,void 0,void 0,function*(){if(!this.cardFields)throw new ri(ti.PaymentNotInitialized);try{const i=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:i.nonce,bin:null===(n=i.details)||void 0===n?void 0:n.bin}}catch(e){if(Yl(e)){const t=this.mapTokenizeError(e,!0);if(t)throw null===(r=null===(i=this.formOptions)||void 0===i?void 0:i.onValidate)||void 0===r||r.call(i,{isValid:!1,errors:t}),new lo(t)}throw e}})}createHostedFields(e){return Jl(this,void 0,void 0,function*(){const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadHostedFields(),i=this.braintreeSDKVersionManager.getSDKVersion()===bi?Object.assign(Object.assign({},e),{preventCursorJumps:!0}):e;return n.create(Object.assign(Object.assign({},i),{client:t}))})}getClient(){return Jl(this,void 0,void 0,function*(){if(!this.clientToken)throw new ri(ti.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($l(e)){const n={};return null==t||t.forEach(e=>{(e=>Object.values(Ni).includes(e))(e)&&(n[e]=!1)}),ue({number:Object.assign({container:`#${e.cardNumber.containerId}`,placeholder:e.cardNumber.placeholder,internalLabel:e.cardNumber.accessibilityLabel},Object.keys(n).length>0?{supportedCardBrands:n}:{}),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}},J)}return ue({number:e.cardNumberVerification&&{container:`#${e.cardNumberVerification.containerId}`,placeholder:e.cardNumberVerification.placeholder},cvv:e.cardCodeVerification&&{container:`#${e.cardCodeVerification.containerId}`,placeholder:e.cardCodeVerification.placeholder}},J)}mapStyleOptions(e){const t=(e={})=>ue({color:e.color,"font-family":e.fontFamily,"font-size":e.fontSize,"font-weight":e.fontWeight},J);return{input:t(e.default),".invalid":t(e.error),":focus":t(e.focus)}}mapFieldType(e){switch(e){case"number":return this.type===Kl.StoredCardVerification?ji.CardNumberVerification:ji.CardNumber;case"expirationDate":return ji.CardExpiry;case"cvv":return this.type===Kl.StoredCardVerification?ji.CardCodeVerification:ji.CardCode;case"cardholderName":return ji.CardName;default:throw new Error("Unexpected field type")}}mapErrors(e){const t={};if(e)for(const[n,i]of Object.entries(e))if(i&&this.isValidParam(n)){const{isValid:e,isEmpty:r,isPotentiallyValid:o}=i;t[n]={isValid:e,isEmpty:r,isPotentiallyValid:o}}return t}mapValidationErrors(e){return Object.keys(e).reduce((t,n)=>{var i;return Object.assign(Object.assign({},t),{[this.mapFieldType(n)]:(null===(i=e[n])||void 0===i?void 0:i.isValid)?void 0:[this.createInvalidError(this.mapFieldType(n))]})},{})}mapTokenizeError(e,t=!1){var n,i;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===(i=null===(n=e.details)||void 0===n?void 0:n.invalidFieldKeys)||void 0===i?void 0:i.reduce((e,t)=>{const n=this.mapFieldType(t);return Object.assign(Object.assign({},e),{[n]:[this.createInvalidError(n)]})},{})}createRequiredError(e){var t;return{fieldType:e,message:null!==(t={[ji.CardCode]:"CVV is required",[ji.CardCodeVerification]:"CVV is required",[ji.CardNumber]:"Credit card number is required",[ji.CardNumberVerification]:"Credit card number is required",[ji.CardExpiry]:"Expiration date is required",[ji.CardName]:"Full name is required"}[e])&&void 0!==t?t:"Field is required",type:"required"}}createInvalidError(e){var t,n,i,r;const o={[ji.CardCode]:{message:"Invalid card code",type:"invalid_card_code"},[ji.CardCodeVerification]:{message:"Invalid card code",type:"invalid_card_code"},[ji.CardNumber]:{message:"Invalid card number",type:"invalid_card_number"},[ji.CardNumberVerification]:{message:"Invalid card number",type:"invalid_card_number"},[ji.CardExpiry]:{message:"Invalid card expiry",type:"invalid_card_expiry"},[ji.CardName]:{message:"Invalid card name",type:"invalid_card_name"}};return{fieldType:e,message:null!==(n=null===(t=o[e])||void 0===t?void 0:t.message)&&void 0!==n?n:"Invalid field",type:null!==(r=null===(i=o[e])||void 0===i?void 0:i.type)&&void 0!==r?r:"invalid"}}isValidForm(e){return Object.keys(e.fields).every(t=>{var n;return null===(n=e.fields[t])||void 0===n?void 0:n.isValid})}isValidParam(e){return["number","cvv","expirationDate","postalCode","cardholderName","cardType"].includes(e)}}const Ql=fi(e=>{const t=window,n=new Ei(e),i=new Hi(a(),t,n),r=new So(i,t),o=new Zl(i,n);return new Wl(e,r,o)},[{id:"braintree"}]);var Xl=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},eu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n};class tu{constructor(e){this._paymentIntegrationService=e}execute(e,t){var n,i;return this._isHostedPaymentFormEnabled(null===(n=e.payment)||void 0===n?void 0:n.methodId,null===(i=e.payment)||void 0===i?void 0:i.gatewayId)&&this._shouldRenderHostedForm?this._executeWithHostedForm(e,t):this._executeWithoutHostedForm(e,t)}initialize(e){if(!this._isHostedPaymentFormEnabled(null==e?void 0:e.methodId,null==e?void 0:e.gatewayId)||!this._isHostedFieldAvailable(e))return this._shouldRenderHostedForm=!1,Promise.resolve();const t=e&&e.creditCard&&e.creditCard.form,n=this._paymentIntegrationService.getState(),{paymentSettings:{bigpayBaseUrl:i=""}={}}=n.getStoreConfigOrThrow();if(!t)throw new vi;const r=this._paymentIntegrationService.createHostedForm(i,t);return r.attach().then(()=>(this._shouldRenderHostedForm=!0,this._hostedForm=r,Promise.resolve()))}deinitialize(){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve()}finalize(){return Promise.reject(new Cd)}_executeWithoutHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t),yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))})}_executeWithHostedForm(e,t){return Xl(this,void 0,void 0,function*(){const{payment:n}=e,i=eu(e,["payment"]),r=this._hostedForm;if(!r)throw new ri(ti.PaymentNotInitialized);if(!n||!n.methodId)throw new co(["payment.methodId"]);yield this._paymentIntegrationService.submitOrder(i,t),yield r.validate().then(()=>r.submit(n))})}_isHostedPaymentFormEnabled(e,t){return!!e&&!0===this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}var nu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class iu extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.cbaMGPSScriptLoader=t,this.sessionId=""}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return nu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{methodId:n}=e;yield this.paymentIntegrationService.loadPaymentMethod(n);const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(n);if(!function(e){return"object"==typeof e&&null!==e&&"initializationData"in e&&"object"==typeof e.initializationData&&null!==e.initializationData&&"merchantId"in e.initializationData&&"string"==typeof e.initializationData.merchantId&&("boolean"==typeof e.initializationData.isTestModeFlagEnabled||void 0===e.initializationData.isTestModeFlagEnabled)}(r))throw new ni(ei.MissingPaymentMethod);const{clientToken:o,initializationData:{isTestModeFlagEnabled:a=!1,merchantId:s},config:{is3dsEnabled:d}}=r;if(d){if(this.threeDSjs=yield this.cbaMGPSScriptLoader.load(a),!this.threeDSjs)throw new ri(ti.PaymentNotInitialized);if(!o||!s)throw new ni(ei.MissingPaymentMethod);if(this.sessionId=o,this.locale=i.getLocale(),!this.locale)throw new ni(ei.MissingCart);yield this.threeDSjs.configure({merchantId:s,sessionId:this.sessionId,callback:()=>{var e;if(null===(e=this.threeDSjs)||void 0===e?void 0:e.isConfigured())return this.paymentIntegrationService.getState();throw new Qr("Failed to configure 3DS API.")},configuration:{userLanguage:this.locale,wsVersion:62}})}return Promise.resolve()})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return nu(this,void 0,void 0,function*(){const{payment:i}=e,r=i&&i.paymentData;if(!i||!r)throw new co(["payment.paymentData"]);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i.methodId),{is3dsEnabled:a}=o.config;if(a){const t=Object.assign(Object.assign({},r),{threeDSecure:{token:this.sessionId}});e.payment&&(e.payment.paymentData=t)}return n.execute.call(this,e,t).catch(e=>{if(!a||!pa(e)||!fe(e.body.errors,{code:"three_d_secure_required"}))return Promise.reject(e);const t=this.paymentIntegrationService.getState(),n=t.getOrder(),{storeProfile:{storeId:i}}=t.getStoreConfigOrThrow();if(!n||!this.sessionId)throw new ni(ei.MissingCheckout);const r=`${i}_${n.orderId}`;if("object"!=typeof(o=e.body)||null===o||!("three_ds_result"in o)||"object"!=typeof o.three_ds_result||null===o.three_ds_result||!("token"in o.three_ds_result)||"string"!=typeof o.three_ds_result.token)throw new nr;var o;const{three_ds_result:{token:s}}=e.body;return s?this.initiateAuthentication(r,s):Promise.reject(e)})})}finalize(e){return nu(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}deinitialize(){return this.threeDSjs=void 0,this.sessionId="",super.deinitialize()}initiateAuthentication(e,t){return nu(this,void 0,void 0,function*(){const n=yield new Promise((n,i)=>{if(!this.threeDSjs)throw new ri(ti.PaymentNotInitialized);this.threeDSjs.initiateAuthentication(e,t,e=>{const t=e.error;return t?i(new Qr(t.msg)):this.threeDSjs&&"PROCEED"===e.gatewayRecommendation?n(e.restApiResponse):i(new Qr)})});if(n.transaction&&"AUTHENTICATION_AVAILABLE"===n.transaction.authenticationStatus)return this.authenticatePayer(e,t);throw new Qr})}authenticatePayer(e,t,n=1){return nu(this,void 0,void 0,function*(){return new Promise((i,r)=>{if(!this.threeDSjs)return r(new ri(ti.PaymentNotInitialized));this.threeDSjs.authenticatePayer(e,t,i=>nu(this,void 0,void 0,function*(){const o=i.error;return o?o.cause&&"SERVER_BUSY"===o.cause&&n<5?(yield new Promise(e=>setTimeout(e,3e3)),this.authenticatePayer(e,t,++n)):r(new Qr):new Promise(ce)}),{fullScreenRedirect:!0})})})}}class ru{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e){return t=this,n=void 0,r=function*(){if(yield this._scriptLoader.loadScript(`//${e?"test":"ap"}-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js`),!this._window.ThreeDS)throw new mi;return this._window.ThreeDS},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const ou=fi(e=>new iu(e,new ru(a())),[{id:"cba_mpgs"}]);var au;!function(e){e.OffsiteRedirect="offsite_redirect"}(au||(au={}));class su extends tu{constructor(e){super(e),this.paymentIntegrationService=e}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new Cd)}_executeWithHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=this._hostedForm;if(!r)throw new ri(ti.PaymentNotInitialized);if(!n||!n.methodId)throw new co(["payment.methodId"]);try{yield r.validate(),yield this.paymentIntegrationService.submitOrder(i,t),yield r.submit(n)}catch(e){return this._processResponse(e)}this.paymentIntegrationService.loadCurrentOrder()},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_processResponse(e){if(!pa(e))return Promise.reject(e);const t=e.body.additional_action_required;return t&&t.type===au.OffsiteRedirect?this._performRedirect(t):Promise.reject(e)}_performRedirect(e){return new Promise(()=>{window.location.replace(e.data.redirect_url)})}}class du extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(n.methodId,r)})}))}catch(e){return this._processResponse(e)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_createFormattedPayload(e,t){if("fawry"===e&&"customerMobile"in t&&"customerEmail"in t){const e=t;return{customerMobile:e.customerMobile,customerEmail:e.customerEmail}}}}const cu=fi(e=>new du(e),[{gateway:"checkoutcom",id:"fawry"}]);function lu(e){return pa(e)&&fe(e.body.errors,{code:"three_d_secure_required"})}var uu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})},hu=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n};class pu extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.formPoster=t}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new Cd)}_executeWithoutHostedForm(e,t){return uu(this,void 0,void 0,function*(){const{payment:n}=e,i=hu(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this.paymentIntegrationService.submitOrder(i,t);try{yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))}catch(e){return lu(e)?this._handleThreeDSecure(e):Promise.reject(e)}})}_executeWithHostedForm(e,t){return uu(this,void 0,void 0,function*(){const{payment:n}=e,i=hu(e,["payment"]),r=this._hostedForm;if(!r)throw new ri(ti.PaymentNotInitialized);if(!n||!n.methodId)throw new co(["payment.methodId"]);try{yield r.validate(),yield this.paymentIntegrationService.submitOrder(i,t),yield r.submit(n)}catch(e){return lu(e)?this._handleThreeDSecure(e):Promise.reject(e)}this.paymentIntegrationService.loadCurrentOrder()})}_handleThreeDSecure(e){const{acs_url:t,payer_auth_request:n,callback_url:i,merchant_data:r}=e.body.three_ds_result;return new Promise(()=>this.formPoster.postForm(t,{PaReq:n||null,TermUrl:i||null,MD:r||null}))}}const mu=fi(e=>new pu(e,Ee()),[{gateway:"checkoutcom",id:"credit_card"},{gateway:"checkoutcom",id:"card"}]);class yu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=null==n?void 0:n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(n.methodId,r)})}))}catch(e){return this._processResponse(e)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_createFormattedPayload(e,t){const n={iban:"",bic:""},{iban:i,bic:r}="iban"in t&&"bic"in t?t:n;return"sepa"===e&&document&&(n.iban=i,n.bic=r),n}}const gu=fi(e=>new yu(e),[{gateway:"checkoutcom",id:"sepa"}]);class fu extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=null==n?void 0:n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(n.methodId,r)})}))}catch(e){return this._processResponse(e)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_createFormattedPayload(e,t){if("ideal"===e&&"bic"in t)return{bic:t.bic}}}const vu=fi(e=>new fu(e),[{gateway:"checkoutcom",id:"ideal"}]);const _u=["boleto","oxxo","qpay","ideal"];class Su extends su{_executeWithoutHostedForm(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=null==n?void 0:n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(n.methodId,r)})}))}catch(e){return this._processResponse(e)}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_createFormattedPayload(e,t){const n={ccDocument:""},i="ccDocument"in t?t.ccDocument:"";return-1!==_u.indexOf(e)&&i&&(n.ccDocument=i),n}}const Iu=fi(e=>new Su(e),[{gateway:"checkoutcom"}]);var wu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Cu{constructor(e,t){this._paymentIntegrationService=e,this._clearpayScriptLoader=t}initialize(e){return wu(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:t}=this._paymentIntegrationService.getState(),n=t(e.methodId,e.gatewayId),i=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features;this._clearpaySdk=yield this._clearpayScriptLoader.load(n,i)})}deinitialize(){return this._clearpaySdk=void 0,Promise.resolve()}execute(e,t){return wu(this,void 0,void 0,function*(){const{gatewayId:n,methodId:i}=e.payment||{};if(!n||!i)throw new co(["payment.gatewayId","payment.methodId"]);const r=this._paymentIntegrationService.getState(),{isStoreCreditApplied:o}=r.getCheckoutOrThrow();yield this._paymentIntegrationService.applyStoreCredit(o),yield this._paymentIntegrationService.validateCheckout(r.getCheckout(),t);const{countryCode:a}=r.getBillingAddressOrThrow();if(!this._isCountrySupported(a))throw new vi("Unable to proceed because billing country is not supported.");return yield this._loadPaymentMethod(n,i,t),yield this._redirectToClearpay(a,this._paymentIntegrationService.getState().getPaymentMethod(i,n)),new Promise(ce)})}finalize(e){var t,n,i;return wu(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new ni(ei.MissingCheckout);if(!a||!a.payment.token)throw new ni(ei.MissingCheckoutConfig);const s={methodId:o.providerId,paymentData:{nonce:a.payment.token}};yield this._paymentIntegrationService.submitOrder({},e);try{yield this._paymentIntegrationService.submitPayment(s)}catch(e){if(yield this._paymentIntegrationService.forgetCheckout(o.providerId),yield this._paymentIntegrationService.loadPaymentMethods(),pa(e))throw new Kd(null===(i=null===(n=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===i?void 0:i.message)}})}_redirectToClearpay(e,t){return wu(this,void 0,void 0,function*(){if(!this._clearpaySdk||!t||!t.clientToken)throw new ri(ti.PaymentNotInitialized);return this._clearpaySdk.initialize({countryCode:e}),this._clearpaySdk.redirect({token:t.clientToken}),Promise.resolve()})}_isCountrySupported(e){return"GB"===e}_loadPaymentMethod(e,t,n){var i;return wu(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},n),{params:Object.assign(Object.assign({},null==n?void 0:n.params),{method:t})}))}catch(e){if(e instanceof nr&&422===(null===(i=e.body)||void 0===i?void 0:i.status))throw new vi("Clearpay can't process your payment for this order, please try another payment method");throw e}})}}class bu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t={}){return n=this,i=void 0,o=function*(){if(yield this._scriptLoader.loadScript(this._getScriptUrl(e.config.testMode,t)),!this._window.AfterPay)throw new mi;return this._window.AfterPay},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}_getScriptUrl(e,t={}){const n=Ci(t,"PI-4555.clearpay_add_https_to_prod_script",!1);return e?n?"https://portal.sandbox.clearpay.co.uk/afterpay-async.js":"//portal.sandbox.clearpay.co.uk/afterpay-async.js":n?"https://portal.clearpay.co.uk/afterpay-async.js":"//portal.clearpay.co.uk/afterpay-async.js"}}const Pu=fi(e=>new Cu(e,new bu(a())),[{gateway:"clearpay"},{id:"clearpay"}]),Ou=fi(e=>new tu(e),[{default:!0}]);var Eu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Au{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return Eu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode),yield this._cardinalClient.configure(yield this._getClientToken(e))})}start(e,t,n,i){return Eu(this,void 0,void 0,function*(){const{getCardInstrument:r,getPaymentMethodOrThrow:o}=this._paymentIntegrationService.getState(),{payment:{methodId:a="",paymentData:s={}}={}}=t,d=Nd(s)&&r(s.instrumentId),c=d?d.iin:i&&i.getBin();c&&(yield this._cardinalClient.runBinProcess(c));try{return yield e(de(t,{payment:{paymentData:{threeDSecure:{token:o(a).clientToken}}}}),n)}catch(e){if(!pa(e)||!fe(e.body.errors,{code:"three_d_secure_required"}))throw e;const n=yield this._cardinalClient.getThreeDSecureData(e.body.three_ds_result,this._getOrderData());if(!i)return void(yield this._paymentIntegrationService.submitPayment(de(t.payment,{paymentData:{threeDSecure:n}})));yield i.submit(de(t.payment,{paymentData:{threeDSecure:n}}))}})}_getClientToken(e){return Eu(this,void 0,void 0,function*(){return e.clientToken?e.clientToken:(yield this._paymentIntegrationService.loadPaymentMethod(e.id),this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.id).clientToken||"")})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),i=e.getCheckoutOrThrow(),r=e.getOrderOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i.cart.currency.code,id:r.orderId.toString(),amount:i.cart.cartAmount}}}const Tu=[100004,1010,1011,1020];var ku,Du,Mu,zu,xu,Nu,Ru;!function(e){e.SetupCompleted="payments.setupComplete",e.Validated="payments.validated"}(ku||(ku={})),function(e){e.Init="init",e.Complete="complete",e.Confirm="confirm"}(Du||(Du={})),function(e){e.Success="SUCCESS",e.NoAction="NOACTION",e.Failure="FAILURE",e.Error="ERROR"}(Mu||(Mu={})),function(e){e.CCA="CCA",e.Paypal="Paypal",e.Wallet="Wallet",e.VisaCheckout="VisaCheckout",e.ApplePay="ApplePay",e.DiscoverWallet="DiscoverWallet"}(zu||(zu={})),function(e){e.BinProcess="bin.process"}(xu||(xu={})),function(e){e.CCA="cca"}(Nu||(Nu={})),function(e){e.Yes="Y",e.No="N"}(Ru||(Ru={}));class Fu{constructor(e){this._scriptLoader=e,this._provider="",this._testMode=!1,this._configurationToken=""}load(e,t=!1){return this._provider=e,this._testMode=t,this._sdk||(this._sdk=this._scriptLoader.load(e,t)),this._sdk.then(ce)}configure(e){if(this._configurationToken){if(this._configurationToken===e)return Promise.resolve();this._sdk=this._scriptLoader.load(`${this._provider}.${Date.now()}`,this._testMode)}return this._getClientSDK().then(t=>new Promise((n,i)=>{t.on(ku.SetupCompleted,()=>{t.off(ku.SetupCompleted),t.off(ku.Validated),this._configurationToken=e,n()}),t.on(ku.Validated,e=>{t.off(ku.SetupCompleted),t.off(ku.Validated),e.ActionCode===Mu.Error&&(H(Tu,e.ErrorNumber)&&i(new ni(ei.MissingPaymentMethod)),i(new Qr(e.ErrorDescription)))}),t.setup(Du.Init,{jwt:e})}))}runBinProcess(e){return this._getClientSDK().then(t=>t.trigger(xu.BinProcess,e).catch(ce)).then(e=>{if(!e||!e.Status)throw new ri(ti.PaymentNotInitialized)})}getThreeDSecureData(e,t){return this._getClientSDK().then(n=>new Promise((i,r)=>{n.on(ku.Validated,(e,t)=>{if(n.off(ku.Validated),!t)return r(new Qr(e.ErrorDescription?e.ErrorDescription:"An error was encountered while processing the transaction."));if(!e.ActionCode)return i({token:t});switch(e.ActionCode){case Mu.Success:return i({token:t});case Mu.NoAction:return e.ErrorNumber>0?r(new Qr(e.ErrorDescription)):e.Payment&&e.Payment.ExtendedData&&e.Payment.ExtendedData.SignatureVerification===Ru.Yes?i({token:t}):r(new Qr("Transaction signature could not be validated."));case Mu.Failure:return r(new Qr("User failed authentication or an error was encountered while processing the transaction."));case Mu.Error:return r(new Qr(e.ErrorDescription))}});const o={AcsUrl:e.acs_url,Payload:e.merchant_data},a=this._mapToPartialOrder(t,e.payer_auth_request);n.continue(Nu.CCA,o,a)}))}_mapToPartialOrder(e,t){const n={BillingAddress:this._mapToCardinalAddress(e.billingAddress)};return e.paymentData&&(n.Account=this._mapToCardinalAccount(e.paymentData)),e.billingAddress.email&&(n.Email1=e.billingAddress.email),e.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(e.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:e.id,Amount:e.amount,CurrencyCode:e.currencyCode,OrderChannel:"S",TransactionId:t}}}_mapToCardinalAccount(e){return{AccountNumber:Number(e.ccNumber),ExpirationMonth:Number(e.ccExpiry.month),ExpirationYear:Number(e.ccExpiry.year),NameOnAccount:e.ccName,CardCode:Number(e.ccCvv)}}_mapToCardinalAddress(e){const t={FirstName:e.firstName,LastName:e.lastName,Address1:e.address1,City:e.city,State:e.stateOrProvince,PostalCode:e.postalCode,CountryCode:e.countryCode};return e.address2&&(t.Address2=e.address2),e.phone&&(t.Phone1=e.phone),t}_getClientSDK(){if(!this._sdk)throw new ri(ti.PaymentNotInitialized);return this._sdk}}class Lu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t){const n=t?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js";return this._scriptLoader.loadScript(`${n}?v=${e}`).then(()=>{if(!this._window.Cardinal)throw new mi;return this._window.Cardinal})}}var ju=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Bu extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return ju(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return ju(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Uu=fi(e=>new Bu(e,new Au(e,new Fu(new Lu(a())))),[{id:"cybersource"}]);var qu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vu{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return qu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode)})}start(e,t,n,i){var r,o,a,s;return qu(this,void 0,void 0,function*(){const{getCardInstrument:d}=this._paymentIntegrationService.getState(),{payment:c={methodId:""}}=t,{paymentData:l={}}=c;try{return yield e(t,n)}catch(e){if(pa(e)&&"additional_action_required"===(null===(r=e.body)||void 0===r?void 0:r.status)){const t=null===(a=null===(o=e.body.additional_action_required)||void 0===o?void 0:o.data)||void 0===a?void 0:a.token,n=null===(s=e.body.three_ds_result)||void 0===s?void 0:s.payer_auth_request;yield this._cardinalClient.configure(t);const r=this._getBin(l,d,i);r&&(yield this._cardinalClient.runBinProcess(r));try{return yield this._submitPayment(c,{xid:n},i)}catch(e){if(pa(e)&&fe(e.body.errors,{code:"three_d_secure_required"})){const t=e.body.three_ds_result,n=null==t?void 0:t.payer_auth_request;return yield this._cardinalClient.getThreeDSecureData(t,this._getOrderData()),this._submitPayment(c,{token:n},i)}throw e}}throw e}})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),n=e.getShippingAddress(),{cart:{currency:{code:i},cartAmount:r}}=e.getCheckoutOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:i,id:e.getOrderOrThrow().orderId.toString(),amount:r}}_submitPayment(e,t,n){return qu(this,void 0,void 0,function*(){const i=de({},e,{paymentData:{threeDSecure:t}});n||(yield this._paymentIntegrationService.submitPayment(i)),yield null==n?void 0:n.submit(i)})}_getBin(e,t,n){const i=Nd(e)&&t(e.instrumentId),r=function(e){const t=e;return!Nd(t)&&"string"==typeof t.ccName&&"string"==typeof t.ccNumber&&"object"==typeof t.ccExpiry&&"string"==typeof t.ccExpiry.month&&"string"==typeof t.ccExpiry.year}(e)&&e.ccNumber,o=n?n.getBin():r;return(i?i.iin:o)||""}}var Gu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hu extends tu{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Gu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),i=n(e.methodId);i.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(i))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Gu(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(i).config.is3dsEnabled?this._threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const Wu=fi(e=>new Hu(e,new Vu(e,new Fu(new Lu(a())))),[{id:"cybersourcev2"},{id:"bnz"}]);function $u(e){return"object"==typeof e&&null!==e&&"errors"in e&&Array.isArray(e.errors)&&"code"in e.errors[0]&&"string"==typeof e.errors[0].code&&"provider_data"in e&&"object"==typeof e.provider_data}var Yu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ku extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ni(ei.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Yu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}processAdditionalAction(e){return Yu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ti.PaymentNotInitialized);return this._adyenClient}}var Ju=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Zu{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t,this._isDeinitializationBlocked=!1,this._loadingIndicator=new fd({containerStyles:yd})}initialize(e){var t,n;return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!na(e.methodId))throw new vi('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!(null==i?void 0:i.walletButton))throw new vi("Unable to proceed without valid options.");const{walletButton:r,loadingContainerId:o}=i,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(i,["walletButton","loadingContainerId"]);this._loadingIndicatorContainer=o,yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());const s=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(this._getMethodId());this._googlePayPaymentProcessor.setIsWebViewExperimentOn(!!(null===(t=s.initializationData)||void 0===t?void 0:t.isWebViewExperimentOn)),yield this._googlePayPaymentProcessor.initialize(()=>s,this._getGooglePayClientOptions(null===(n=s.initializationData)||void 0===n?void 0:n.storeCountry)),this._addPaymentButton(r,a)})}execute({payment:e}){return Ju(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();const t=yield this._googlePayPaymentProcessor.getNonce(e.methodId),n=yield this._googlePayPaymentProcessor.extraPaymentData();try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign({nonce:t},n)}))}catch(t){yield this._googlePayPaymentProcessor.processAdditionalAction(t,e.methodId)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this._isDeinitializationBlocked||(this._clickListener&&(null===(e=this._paymentButton)||void 0===e||e.removeEventListener("click",this._clickListener)),this._paymentButton=void 0,this._clickListener=void 0,this._methodId=void 0),Promise.resolve()}_addPaymentButton(e,t){if(this._paymentButton)return;const n=document.getElementById(e);if(!n)throw new vi("Unable to proceed without a walletButton.");this._paymentButton=n,this._clickListener=this._handleClick(t),this._paymentButton.addEventListener("click",this._clickListener)}_handleClick({onPaymentSelect:e,onError:t}){return n=>Ju(this,void 0,void 0,function*(){n.preventDefault();try{this._googlePayPaymentProcessor.setShouldRequestShipping(!1),yield this._googlePayPaymentProcessor.initializeWidget(),this._isDirectPayOnClickEnabled()?yield this._interactWithPaymentSheetAndPay():yield this._interactWithPaymentSheet()}catch(e){let n=e;if(this._toggleLoadingIndicator(!1),ta(e)){if("CANCELED"===e.statusCode)throw new Wi;n=new Qr(JSON.stringify(e))}throw null==t||t(new Qr("An error occurred while requesting your Google Pay payment details.")),n}finally{this._toggleBlockDeinitialization(!1)}null==e||e()})}_interactWithPaymentSheetAndPay(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet();this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const t=this._getMethodId(),n=this._paymentIntegrationService.getState(),{features:i}=n.getStoreConfigOrThrow().checkoutSettings,r=Ci(i,"PI-5031.google_pay_dont_override_address"),o=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);o&&!r&&(yield this._paymentIntegrationService.updateBillingAddress(o)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(t,e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(t);const a=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(t);yield this._googlePayPaymentProcessor.initialize(()=>a),yield this.execute({useStoreCredit:!1,payment:{methodId:t}}),this._completeCheckoutFlow()})}_completeCheckoutFlow(){window.location.replace("/checkout/order-confirmation"),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)}_interactWithPaymentSheet(){return Ju(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._paymentIntegrationService.getState(),{features:n}=t.getStoreConfigOrThrow().checkoutSettings,i=Ci(n,"PI-5031.google_pay_dont_override_address");this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const r=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);r&&!i&&(yield this._paymentIntegrationService.updateBillingAddress(r)),yield this._googlePayPaymentProcessor.setExternalCheckoutXhr(this._getMethodId(),e),yield this._paymentIntegrationService.loadCheckout(),yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),this._toggleLoadingIndicator(!1),this._toggleBlockDeinitialization(!1)})}_getMethodId(){return ii(this._methodId,()=>new ri(ti.PaymentNotInitialized))}_getIsSignedInOrThrow(){return Ju(this,void 0,void 0,function*(){try{return!!(yield this._googlePayPaymentProcessor.getNonce(this._getMethodId()))}catch(e){if(e instanceof ni&&e.subtype===ei.MissingPaymentToken)return!1;throw e}})}_handleOfferTrigger(e){return Ju(this,void 0,void 0,function*(){let t=!1,n="Sign in to Google Pay first to apply or remove promo codes.";try{t=yield this._getIsSignedInOrThrow()}catch(e){e instanceof ni&&(n=e.message)}if(t){const{newOfferInfo:t,error:n}=yield this._googlePayPaymentProcessor.handleCoupons(e);return{newOfferInfo:t,error:n}}return{error:{reason:Ko.OFFER_INVALID,message:n,intent:Jo.OFFER}}})}_getGooglePayClientOptions(e){return this._googlePayPaymentProcessor.isWebViewWithRestrictions()?{}:{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,offerData:n})=>Ju(this,void 0,void 0,function*(){if(t!==Jo.INITIALIZE&&t!==Jo.OFFER)return;const{offerChangeTriggers:i}=this._googlePayPaymentProcessor.getCallbackTriggers(),{newOfferInfo:r,error:o}=i.includes(t)?yield this._handleOfferTrigger(n):{},a=o;yield this._paymentIntegrationService.loadCheckout();const{code:s}=this._paymentIntegrationService.getState().getCartOrThrow().currency,d=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:s,totalPriceStatus:Wo.FINAL,totalPrice:d})},r&&{newOfferInfo:r}),a&&{error:a})})}}}_isDirectPayOnClickEnabled(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return Ci(e,"PI-5111.google_pay_direct_pay_on_click")}_toggleBlockDeinitialization(e){this._isDeinitializationBlocked=e}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this._loadingIndicator.show(this._loadingIndicatorContainer):this._loadingIndicator.hide()}}const Qu=fi(e=>new Zu(e,new aa(da(),new Ku(e,new zd(a(),s())),n(),Ee())),[{id:"googlepayadyenv2"}]);var Xu=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class eh extends ea{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,n){const i=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){yield i.initialize.call(this,e,t,n);const r=i.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new ni(ei.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}processAdditionalAction(e){return Xu(this,void 0,void 0,function*(){if(!pa(e)||!$u(e.body))throw e;const t=yield this._handleAction(e.body.provider_data);try{return yield this._service.submitPayment(t)}catch(e){return this.processAdditionalAction(e)}})}getNonce(e){const t=Object.create(null,{getNonce:{get:()=>super.getNonce},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Xu(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),i=t.getPaymentMethod.call(this);return JSON.stringify({type:i.method,googlePayToken:n,browser_info:ss()})})}_handleAction(e){return new Promise((t,n)=>{const i=JSON.parse(e.action);this._getAdyenClient().createFromAction(i,{onAdditionalDetails:e=>{const n={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(n)},size:"05",onError:e=>n(e)}).mount("body"),n(new Wi)})}_getAdyenClient(){if(!this._adyenClient)throw new ri(ti.PaymentNotInitialized);return this._adyenClient}}const th=fi(e=>new Zu(e,new aa(da(),new eh(e,new jd(a(),s())),n(),Ee())),[{id:"googlepayadyenv3"}]),nh=fi(e=>new Zu(e,new aa(da(),new ua(e),n(),Ee())),[{id:"googlepayauthorizenet"}]),ih=fi(e=>{const t=n();return new Zu(e,new aa(da(),new ga(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),rh=fi(e=>new Zu(e,new aa(da(),new va(e),n(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),oh=fi(e=>new Zu(e,new aa(da(),new Ia(e),n(),Ee())),[{id:"googlepayorbital"}]),ah=fi(e=>new Zu(e,new aa(da(),new Ua(e,new Ra(a())),n(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),sh=fi(e=>new Zu(e,new aa(da(),new Ga(e),n(),Ee())),[{id:"googlepayworldpayaccess"}]),dh=fi(e=>{const t=n(),i=window,r=new Ei(e),o=new Ui(new Hi(a(),i,r));return new Zu(e,new aa(da(),new $a(e,o),t,Ee()))},[{id:"googlepaybraintree"}]);var ch,lh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(ch||(ch={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(lh||(lh={}));var uh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalCommerceSdk=n,this._requestSender=i}execute({payment:e}){return uh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return uh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ni(ei.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalCommerceSdk.getPayPalGooglePaySdk(i,r,n.getLocale(),!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===ch.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==ch.Approved)throw new vi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return uh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepaypaypalcommercecheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const ph=fi(e=>{const t=new Xa(a());return new hh(e,new aa(da(),new ns(e,t),n(),Ee()),t,n())},[{id:"googlepaypaypalcommerce"}]);var mh,yh;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(mh||(mh={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(yh||(yh={}));var gh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fh extends Zu{constructor(e,t,n,i){super(e,t),this._payPalSdkHelper=n,this._requestSender=i}execute({payment:e}){return gh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new co(["payment"]);const t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow().id,{initializationData:i}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(n),{card_information:o}=i||{},a=yield this._googlePayPaymentProcessor.getNonce(e.methodId),s={tokenizationData:{type:"PAYMENT_GATEWAY",token:atob(a)},info:{cardNetwork:(null==o?void 0:o.type)||"",cardDetails:(null==o?void 0:o.number)||""},type:"CARD"};yield this.confirmOrder(r,s),yield this._paymentIntegrationService.submitOrder();try{const t={formattedPayload:{method_id:e.methodId,paypal_account:{order_id:r}}};yield this._paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:t})}catch(e){yield this._googlePayPaymentProcessor.processAdditionalAction(e)}})}confirmOrder(e,t){return gh(this,void 0,void 0,function*(){const n=this._paymentIntegrationService.getState(),i=n.getPaymentMethodOrThrow(this._getMethodId());if(!i.initializationData)throw new ni(ei.MissingPaymentMethod);const r=n.getCartOrThrow().currency.code,o=yield this._payPalSdkHelper.getPayPalGooglePaySdk(i,r,!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===mh.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==mh.Approved)throw new vi("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return gh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:n}=yield this._requestSender.post("/api/storefront/payments/googlepay_bigcommerce_paymentscheckout",{headers:Object.assign({"X-API-INTERNAL":hr,"Content-Type":mr.Json},yr),body:t});return n})}}const vh=fi(e=>{const t=new Nr(a());return new fh(e,new aa(da(),new os(e,t),n(),Ee()),t,n())},[{id:"googlepay_bigcommerce_payments"}]),_h=fi(e=>new Zu(e,new aa(da(),new cs(e,Ee()),n(),Ee())),[{id:"googlepaytdonlinemart"}]);class Sh extends Xn{constructor(e,t,n){super(n||"Payment cannot be processed for this order, please select another payment method"),this.type="custom_provider_execute_error",this.name=t,this.subtype=e}}class Ih{constructor(e,t){this.paymentIntegrationService=e,this.formPoster=t}execute(e,t){var n,i,r,o,a;return i=this,r=void 0,a=function*(){const{payment:i}=e,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!(null==i?void 0:i.methodId))throw new co(["payment.methodId"]);yield this.paymentIntegrationService.loadPaymentMethod(i.methodId,t);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i.methodId);if(!(null===(n=o.initializationData)||void 0===n?void 0:n.processable))throw new Sh("payment.humm_not_processable_error","hummNotProcessableError");yield this.paymentIntegrationService.submitOrder(r,t);try{yield this.paymentIntegrationService.submitPayment({methodId:i.methodId})}catch(e){return this.isOffsiteRedirectResponse(e)?this.handleOffsiteRedirectResponse(e):Promise.reject(e)}},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())})}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}handleOffsiteRedirectResponse(e){const t=e.body.additional_action_required.data.redirect_url,n=e.body.provider_data;return new Promise(e=>{this.formPoster.postForm(t,JSON.parse(n),e)})}isOffsiteRedirectResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!t.body)return!1;const n=t.body;return"additional_action_required"===n.status&&!!n.additional_action_required&&"offsite_redirect"===n.additional_action_required.type&&"string"==typeof n.provider_data}}const wh=fi(e=>new Ih(e,Ee()),[{id:"humm"}]),Ch=["AT","BE","CA","CH","CZ","DE","DK","ES","FI","FR","GB","GR","IE","IT","NL","NO","NZ","PL","PT","SE"],bh=["AU"];var Ph=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Oh{constructor(e,t){this.paymentIntegrationService=e,this.klarnaScriptLoader=t}initialize(e){return Ph(this,void 0,void 0,function*(){this.klarnaCredit=yield this.klarnaScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Ph(this,void 0,void 0,function*(){if(!e.payment)throw new vi('Unable to proceed because "payload.payment" argument is not provided.');const n=e.payment,{paymentData:i}=n,r=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(n,["paymentData"]),{authorization_token:o}=yield this.authorize();yield this.paymentIntegrationService.initializePayment(r.methodId,{authorizationToken:o}),yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:r,useStoreCredit:e.useStoreCredit}),t)})}finalize(){return Promise.reject(new Cd)}loadWidget(e){return Ph(this,void 0,void 0,function*(){if(!e.klarna)throw new vi('Unable to load widget because "options.klarna" argument is not provided.');const{methodId:t,klarna:{container:n,onLoad:i}}=e;return yield this.paymentIntegrationService.loadPaymentMethod(t),new Promise(e=>{const r=this.paymentIntegrationService.getState().getPaymentMethod(t);if(!r)throw new ni(ei.MissingPaymentMethod);if(!this.klarnaCredit||!r.clientToken)throw new ri(ti.PaymentNotInitialized);this.klarnaCredit.init({client_token:r.clientToken}),this.klarnaCredit.load({container:n},t=>{i&&i(t),e(t)})})})}getUpdateSessionData(e,t){if(!H([...Ch,...bh],e.countryCode))return{};const n={billing_address:this.mapToKlarnaAddress(e,e.email)};return t&&(n.shipping_address=this.mapToKlarnaAddress(t,e.email)),n}needsStateCode(e){return H(bh,e)}mapToKlarnaAddress(e,t){const n={street_address:e.address1,city:e.city,country:e.countryCode,given_name:e.firstName,family_name:e.lastName,postal_code:e.postalCode,region:this.needsStateCode(e.countryCode)?e.stateOrProvinceCode:e.stateOrProvince,email:t};return e.address2&&(n.street_address2=e.address2),e.phone&&(n.phone=e.phone),n}authorize(){return new Promise((e,t)=>{const n=this.paymentIntegrationService.getState(),i=n.getBillingAddress(),r=n.getShippingAddress();if(!i)throw new ni(ei.MissingBillingAddress);if(!this.klarnaCredit)throw new ri(ti.PaymentNotInitialized);const o=this.getUpdateSessionData(i,r);this.klarnaCredit.authorize(o,n=>n.approved?e(n):n.show_form?t(new Wi):void t(new Xr))})}}class Eh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Credit)||(yield this.scriptLoader.loadScript("//credit.klarnacdn.net/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Credit))throw new mi;return this.klarnaWindow.Klarna.Credit},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}const Ah=fi(e=>new Oh(e,new Eh(a())),[{id:"klarna"}]);var Th=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class kh{constructor(e,t,n){this.paymentIntegrationService=e,this.klarnav2ScriptLoader=t,this.klarnav2TokenUpdater=n}initialize(e){return Th(this,void 0,void 0,function*(){this.klarnaPayments=yield this.klarnav2ScriptLoader.load(),this.unsubscribe=this.paymentIntegrationService.subscribe(t=>{t.isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&this.loadPaymentsWidget(e)},e=>{const t=e.getCheckout();return t&&t.outstandingBalance},e=>{const t=e.getCheckout();return t&&t.coupons}),yield this.loadPaymentsWidget(e)})}deinitialize(){return this.unsubscribe&&this.unsubscribe(),Promise.resolve()}execute(e,t){return Th(this,void 0,void 0,function*(){if(!e.payment)throw new vi('Unable to proceed because "payload.payment" argument is not provided.');const n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e.payment,[]),{gatewayId:i,methodId:r}=n;if(!i)throw new vi('Unable to proceed because "payload.payment.gatewayId" argument is not provided.');const o=this.paymentIntegrationService.getState(),{id:a}=o.getCartOrThrow(),{clientToken:s,initializationData:d}=o.getPaymentMethodOrThrow(r),{klarnaMultipleRadioButton:c}=d||{};yield this.klarnav2TokenUpdater.klarnaOrderInitialization(a,s);const l=this.isKlarnaMultipleRadioButtonEnabled(c,i,r),{authorization_token:u}=yield this.authorizeOrThrow(l,r);yield this.paymentIntegrationService.initializePayment(i,{authorizationToken:u}),yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:n,useStoreCredit:e.useStoreCredit}),t)})}finalize(){return Promise.reject(new Cd)}loadPaymentsWidget(e){return Th(this,void 0,void 0,function*(){if(!e.klarnav2)throw new vi('Unable to load widget because "options.klarnav2" argument is not provided.');const{methodId:t,gatewayId:n,klarnav2:{container:i,onLoad:r}}=e;if(!n)throw new vi('Unable to proceed because "payload.payment.gatewayId" argument is not provided.');const o=this.paymentIntegrationService.getState(),a={params:o.getCartOrThrow().id};return yield this.klarnav2TokenUpdater.updateClientToken(n,{params:a}).catch(()=>{throw new ni(ei.MissingPaymentMethod)}),new Promise(e=>{const a=o.getPaymentMethodOrThrow(t),{klarnaMultipleRadioButton:s}=a.initializationData||{};if(!this.klarnaPayments||!a.clientToken)throw new ri(ti.PaymentNotInitialized);this.klarnaPayments.init({client_token:a.clientToken}),this.klarnaPayments.load({container:i,payment_method_category:this.isKlarnaMultipleRadioButtonEnabled(s,n,t)},t=>{r&&r(t),e(t)})})})}getUpdateSessionData(e,t,n){if(!H([...Ch,...bh],t.countryCode))return{};const i={billing_address:this.mapToKlarnaAddress(e,t,t.email)};return n&&(i.shipping_address=this.mapToKlarnaAddress(e,n,t.email)),i}needsStateCode(e){return H(bh,e)}isKlarnaMultipleRadioButtonEnabled(e,t,n){return e?n:t}mapToKlarnaAddress(e,t,n){const i=this.paymentIntegrationService.getState(),{checkoutSettings:r}=i.getStoreConfigOrThrow(),o=i.getPaymentMethodOrThrow(e),{enableBillie:a}=o.initializationData||{},s={street_address:t.address1,city:t.city,country:t.countryCode,given_name:t.firstName,family_name:t.lastName,postal_code:t.postalCode,region:this.needsStateCode(t.countryCode)?t.stateOrProvinceCode:t.stateOrProvince,email:n};return t.address2&&(s.street_address2=t.address2),t.phone&&(s.phone=t.phone),t.company&&a&&Ci(r.features,"PI-3915.b2b_payment_session_for_klarna")&&(s.organization_name=t.company),s}authorizeOrThrow(e,t){return Th(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const n=this.paymentIntegrationService.getState(),i=n.getBillingAddressOrThrow(),r=n.getShippingAddress(),o=this.getUpdateSessionData(t,i,r);return new Promise((t,n)=>{if(!this.klarnaPayments)return n(new ri(ti.PaymentNotInitialized));this.klarnaPayments.authorize({payment_method_category:e},o,e=>e.approved?t(e):e.show_form?n(new Wi):void n(new Xr))})})}}class Dh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,n,i,r,o;return n=this,i=void 0,o=function*(){if((null===(e=this.klarnaWindow.Klarna)||void 0===e?void 0:e.Payments)||(yield this.scriptLoader.loadScript("https://x.klarnacdn.net/kp/lib/v1/api.js")),!(null===(t=this.klarnaWindow.Klarna)||void 0===t?void 0:t.Payments))throw new mi;return this.klarnaWindow.Klarna.Payments},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())})}}class Mh{constructor(e){this.requestSender=e}updateClientToken(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this.requestSender.get(i,{timeout:t,headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),params:n})}klarnaOrderInitialization(e,t){return n=this,i=void 0,o=function*(){const n={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{cartId:e,clientToken:t}};yield this.requestSender.put("/api/storefront/initialization/klarna",n)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}const zh=fi(e=>{const{getHost:t}=e.getState(),i=n({host:t()});return new kh(e,new Dh(a()),new Mh(i))},[{gateway:"klarna"}]);class xh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return yield this._paymentIntegrationService.submitOrder(e,t),Promise.resolve()},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Nh=fi(e=>new xh(e),[{id:"testgateway"}]);var Rh,Fh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};!function(e){e.CREDIT_CARD="credit_card"}(Rh||(Rh={}));const Lh=["klarnapaylater","klarnasliceit"];class jh{constructor(e,t){this.mollieScriptLoader=e,this.paymentIntegrationService=t}initialize(e){return Fh(this,void 0,void 0,function*(){const{mollie:t,methodId:n,gatewayId:i}=e;if(!t)throw new vi('Unable to initialize payment because "options.mollie" argument is not provided.');if(!n||!i)throw new vi('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.');const r=document.querySelectorAll(".mollie-components-controller");F(r,e=>e.remove());const o=this.paymentIntegrationService.getState(),a=o.getStoreConfigOrThrow();this.initializeOptions=t;const s=o.getPaymentMethodOrThrow(n,i),{config:{merchantId:d,testMode:c}}=s;if(this.locale=o.getLocale(),!d)throw new ni(ei.MissingPaymentMethod);return this.isCreditCard(n)&&t.form&&this.shouldShowTSVHostedForm(n,i)?this.hostedForm=yield this.mountCardVerificationfields(t.form):this.isCreditCard(n)&&(this.mollieClient=yield this.loadMollieJs(d,a.storeProfile.storeLanguage,c),this.mountElements()),this.unsubscribe=()=>{if(this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:e.methodId,gatewayId:e.gatewayId})){const e=document.getElementById(`${i}-${n}-paragraph`);e&&e.remove(),t.disableButton(!1),this.loadPaymentMethodsAllowed(t,n,i)}},this.unsubscribe(),this.loadPaymentMethodsAllowed(t,n,i),Promise.resolve()})}execute(e,t){return Fh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=null==n?void 0:n.paymentData;if(!n||!n.gatewayId||!r)throw new co(["payment","gatewayId","paymentData"]);try{return yield this.paymentIntegrationService.submitOrder(i,t),Nd(r)?yield this.executeWithVaulted(n):this.isCreditCard(n.methodId)?yield this.executeWithCC(n):yield this.executeWithAPM(n)}catch(e){yield this.processAdditionalAction(e)}})}finalize(){return Promise.resolve()}deinitialize(e){if(this.unsubscribe&&this.unsubscribe(),this.hostedForm&&this.hostedForm.detach(),e&&e.methodId&&e.gatewayId&&!this.hostedForm){const t=document.getElementById(`${e.gatewayId}-${e.methodId}`);t&&t.remove()}else e&&e.methodId&&this.isCreditCard(e.methodId)&&this.cardHolderElement&&this.cardNumberElement&&this.verificationCodeElement&&this.expiryDateElement&&(this.cardHolderElement.unmount(),this.cardHolderElement=void 0,this.cardNumberElement.unmount(),this.cardNumberElement=void 0,this.verificationCodeElement.unmount(),this.verificationCodeElement=void 0,this.expiryDateElement.unmount(),this.expiryDateElement=void 0);return this.mollieClient=void 0,Promise.resolve()}executeWithCC(e){return Fh(this,void 0,void 0,function*(){const t=e.paymentData,{shouldSaveInstrument:n=!1,shouldSetAsDefaultInstrument:i=!1}=Bd(t)?t:{},{token:r,error:o}=yield this.getMollieClient().createToken();if(o)return Promise.reject(o);const a={credit_card_token:{token:r},vault_payment_instrument:n,set_as_default_stored_instrument:i,browser_info:ss(),shopper_locale:this.getShopperLocale()};yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:a}}))})}executeWithVaulted(e){return Fh(this,void 0,void 0,function*(){if(this.isHostedPaymentFormEnabled(e.methodId,e.gatewayId)){const t=this.hostedForm;if(!t)throw new ri(ti.PaymentNotInitialized);yield t.validate(),yield t.submit(e),yield this.paymentIntegrationService.loadCurrentOrder()}else yield this.paymentIntegrationService.submitPayment(e)})}executeWithAPM(e){return Fh(this,void 0,void 0,function*(){const t=e.paymentData,n=t&&"issuer"in t?t.issuer:"";yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign(Object.assign({},t),{formattedPayload:{issuer:n,shopper_locale:this.getShopperLocale()}})}))})}isCreditCard(e){return e===Rh.CREDIT_CARD}shouldShowTSVHostedForm(e,t){return this.isHostedPaymentFormEnabled(e,t)&&this.isHostedFieldAvailable()}mountCardVerificationfields(e){return new Promise((t,n)=>Fh(this,void 0,void 0,function*(){try{const n=this.paymentIntegrationService.getState().getStoreConfig(),i=null==n?void 0:n.paymentSettings.bigpayBaseUrl;if(!i)throw new ni(ei.MissingCheckoutConfig);const r=this.paymentIntegrationService.createHostedForm(i,e);yield r.attach(),t(r)}catch(e){n(e)}}))}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:n}=this.paymentIntegrationService.getState();return!0===n(e,t).config.isHostedFormEnabled}isHostedFieldAvailable(){var e;return!!(null===(e=this.getInitializeOptions().form)||void 0===e?void 0:e.fields)}processAdditionalAction(e){if(!pa(e))return Promise.reject(e);if(fe(e.body.errors,{code:"additional_action_required"})){const{additional_action_required:{data:{redirect_url:t}}}=e.body;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ti.PaymentNotInitialized);return this.initializeOptions}loadMollieJs(e,t,n=!1){return this.mollieClient?Promise.resolve(this.mollieClient):this.mollieScriptLoader.load(e,t,n)}getMollieClient(){if(!this.mollieClient)throw new ri(ti.PaymentNotInitialized);return this.mollieClient}getShopperLocale(){if(!this.locale)throw new ri(ti.PaymentNotInitialized);return this.locale}mountElements(){const{containerId:e,cardNumberId:t,cardCvcId:n,cardExpiryId:i,cardHolderId:r,styles:o}=this.getInitializeOptions();let a;e&&(a=document.getElementById(e)),setTimeout(()=>{if(!e||"none"!==(null==a?void 0:a.style.display)){const e=this.getMollieClient();this.cardHolderElement=e.createComponent("cardHolder",{styles:o}),this.cardHolderElement.mount(`#${r}`),this.cardNumberElement=e.createComponent("cardNumber",{styles:o}),this.cardNumberElement.mount(`#${t}`),this.verificationCodeElement=e.createComponent("verificationCode",{styles:o}),this.verificationCodeElement.mount(`#${n}`),this.expiryDateElement=e.createComponent("expiryDate",{styles:o}),this.expiryDateElement.mount(`#${i}`)}},0)}loadPaymentMethodsAllowed(e,t,n){var i;if(Lh.includes(t)){const r=null===(i=this.paymentIntegrationService.getState().getCartOrThrow().lineItems)||void 0===i?void 0:i.digitalItems;if(r&&r.length>0){const{containerId:i}=this.getInitializeOptions();if(i){const r=document.getElementById(i);if(r){const i=document.createElement("p");i.setAttribute("id",`${n}-${t}-paragraph`),e.unsupportedMethodMessage&&(i.innerText=e.unsupportedMethodMessage,r.appendChild(i),e.disableButton(!0))}}}}}}class Bh{constructor(e,t=window){this.scriptLoader=e,this.mollieHostWindow=t}load(e,t,n){return i=this,r=void 0,a=function*(){if(yield this.scriptLoader.loadScript("https://js.mollie.com/v1/mollie.js"),!function(e){return"Mollie"in e}(this.mollieHostWindow))throw new mi;return this.mollieHostWindow.Mollie(e,{locale:t,testmode:n})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a}}const Uh=fi(e=>new jh(new Bh(a()),e),[{gateway:"mollie"},{gateway:"mollie",id:"applepay"}]);var qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const Vh="moneris-payment-iframe";class Gh{constructor(e){this.paymentIntegrationService=e}initialize(e){return qh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{moneris:n,methodId:i}=e;if(!i)throw new vi('Unable to initialize payment because "methodId" argument is not provided.');if(!n)throw new vi('Unable to initialize payment because "options.moneris" argument is not provided.');this.initializeOptions=n;const{config:r,initializationData:o}=t.getPaymentMethodOrThrow(i);if(!(null==o?void 0:o.profileId))throw new ni(ei.MissingPaymentMethod);return n.form&&this.shouldShowTSVHostedForm(i)&&(this.hostedForm=yield this.mountCardVerificationfields(n.form)),this.iframe||(this.iframe=this.createIframe(n.containerId,o,!!r.testMode)),Promise.resolve()})}execute(e,t){return qh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{isStoreCreditApplied:r}=this.paymentIntegrationService.getState().getCheckoutOrThrow();if(r&&(yield this.paymentIntegrationService.applyStoreCredit(r)),yield this.paymentIntegrationService.submitOrder(i,t),!n.paymentData||!Nd(n.paymentData))return this.executeWithCC(n);yield this.executeWithVaulted(n)})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this.hostedForm&&this.hostedForm.detach(),this.windowEventListener&&(window.removeEventListener("message",this.windowEventListener),this.windowEventListener=void 0),this.iframe&&this.iframe.parentNode&&(this.iframe.parentNode.removeChild(this.iframe),this.iframe=void 0),Promise.resolve()}executeWithCC(e){return qh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId).config.testMode,n=e.paymentData||{},i=Bd(n)?n:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o}=i,a=yield new Promise((e,n)=>{if(!this.iframe)throw new ri(ti.PaymentNotInitialized);const i=this.iframe.contentWindow;if(null===i)throw new ri(ti.PaymentNotInitialized);i.postMessage("tokenize",this.monerisURL(!!t)),this.windowEventListener=i=>{if("string"==typeof i.data&&i.origin===`https://${t?"esqa":"www3"}.moneris.com`)try{e(this.handleMonerisResponse(i))}catch(e){n(e)}},window.addEventListener("message",this.windowEventListener)});void 0!==a&&(yield this.paymentIntegrationService.submitPayment({methodId:e.methodId,paymentData:{nonce:a,shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o}}))})}executeWithVaulted(e){return qh(this,void 0,void 0,function*(){if(this.hostedForm){const t=this.hostedForm;return yield t.validate(),yield t.submit(e),this.paymentIntegrationService.loadCurrentOrder()}return this.paymentIntegrationService.submitPayment(e)})}shouldShowTSVHostedForm(e){return this.isHostedPaymentFormEnabled(e)&&this.isHostedFieldAvailable()}isHostedPaymentFormEnabled(e){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e);return Boolean(t.config.isHostedFormEnabled)}isHostedFieldAvailable(){var e;const t=this.getInitializeOptions(),n=ue(null===(e=t.form)||void 0===e?void 0:e.fields,$);return!$(n)}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ti.PaymentNotInitialized);return this.initializeOptions}mountCardVerificationfields(e){var t;return qh(this,void 0,void 0,function*(){const n=null===(t=this.paymentIntegrationService.getState().getStoreConfig())||void 0===t?void 0:t.paymentSettings.bigpayBaseUrl;if(!n)throw new ni(ei.MissingCheckoutConfig);const i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}createIframe(e,t,n,i){const r=document.getElementById(e);if(!r)throw new vi("Unable to create iframe without valid container ID.");const o=document.createElement("iframe"),a={id:t.profileId,pmmsg:!0,display_labels:1,enable_exp:1,enable_cvd:1,css_body:(null==i?void 0:i.cssBody)||"font-family: Arial, Helvetica,sans-serif;background: transparent;",css_textbox:(null==i?void 0:i.cssTextbox)||"border-radius:4px;border: 2px solid rgb(00,00,00);width: 100%;font-weight: 600;padding: 8px 8px;outline: 0;",css_textbox_pan:(null==i?void 0:i.cssTextboxCardNumber)||"width: 240px;",css_textbox_exp:(null==i?void 0:i.cssTextboxExpiryDate)||"margin-bottom: 0;width: calc(30% - 12px);",css_textbox_cvd:(null==i?void 0:i.cssTextboxCVV)||"margin-bottom: 0;width: calc(30% - 12px);",css_input_label:(null==i?void 0:i.cssInputLabel)||"font-size: 10px;position: relative;top: 8px;left: 6px;background: rgb(255,255,255);padding: 3px 2px;color: rgb(66,66,66);font-weight: 600;z-index: 2;",pan_label:t.creditCardLabel||"Credit Card Number",exp_label:t.expiryDateLabel||"Expiration",cvd_label:t.cvdLabel||"CVD"},s=oe(a,(e,t)=>`${t}=${e}`).join("&");return o.width="100%",o.height="100%",o.name=Vh,o.id=Vh,o.style.border="none",o.src=`${this.monerisURL(n)}?${s}`,o.allow="payment",r.appendChild(o),o}handleMonerisResponse(e){const t=JSON.parse(e.data);if("001"!==t.responseCode[0])throw new Error(t.errorMessage);return t.dataKey}monerisURL(e){return`https://${e?"esqa":"www3"}.moneris.com/HPPtoken/index.php`}}const Hh=fi(e=>new Gh(e),[{id:"moneris"}]);class Wh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return n=this,i=void 0,o=function*(){return yield this._paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:e.payment?{methodId:e.payment.methodId}:void 0}),t),Promise.resolve()},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const $h=fi(e=>new Wh(e),[{type:"PAYMENT_TYPE_OFFLINE"}]);var Yh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Kh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return Yh(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=this._shouldSubmitFullPayload(n)?e:i,o=n&&n.paymentData,a=o&&Nd(o)&&o.instrumentId||void 0,s=o&&Bd(o)&&o.shouldSaveInstrument||void 0,d=o&&Bd(o)&&o.shouldSetAsDefaultInstrument||void 0;if(!n)throw new co(["payment"]);const{methodId:c,gatewayId:l}=n;yield this._paymentIntegrationService.submitOrder(r,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:c,gatewayId:l,instrumentId:a,shouldSaveInstrument:s,shouldSetAsDefaultInstrument:d})})}finalize(e){return Yh(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),n=t.getOrder(),i=t.getPaymentStatus();if(!n||i!==dl.ACKNOWLEDGE&&i!==dl.FINALIZE)return Promise.reject(new Cd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_shouldSubmitFullPayload(e){return!!e&&("adyen"===e.gatewayId||"barclaycard"===e.gatewayId)}}const Jh=fi(e=>new Kh(e),[{type:"PAYMENT_TYPE_HOSTED"}]),Zh=function({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};var Qh=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Xh{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.payPalSdkScriptLoader=n,this.loadingIndicator=i}initialize(e){var t;return Qh(this,void 0,void 0,function*(){const{methodId:n,paypalcommerce:i}=e||{};if(this.paypalcommerce=i,!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(n),{container:a,bannerContainerId:s}=i,{orderId:d,paypalBNPLConfiguration:c=[],isPayPalCreditAvailable:l}=o.initializationData||{};if(void 0!==s){if(!document.getElementById(s))return void console.error("Unable to create banner without valid banner container ID.");const e=null==c?void 0:c.find(({id:e})=>"checkout"===e);if(l||!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(o,r.getCartOrThrow().currency.code,r.getLocale());return t&&"function"==typeof(null==t?void 0:t.Messages)?this.renderMessages(t,s,e):void console.error("[BC PayPalCommerce PayLater]: banner could not be rendered, due to issues with loading PayPal SDK")}d?this.orderId=null===(t=o.initializationData)||void 0===t?void 0:t.orderId:(this.loadingIndicatorContainer=null==a?void 0:a.split("#")[1],yield this.paypalIntegrationService.loadPayPalSdk(n),i.onInit&&"function"==typeof i.onInit&&i.onInit(()=>this.renderButton(n,i)),(void 0===i.shouldRenderPayPalButtonOnInitialization||i.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(n,i))})}execute(e,t){var n,i;return Qh(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{onError:a}=this.paypalcommerce||{};if(!r)throw new co(["payment"]);const{methodId:s,paymentData:d}=r;if(this.isPayPalVaultedInstrumentPaymentData(d)&&!this.orderId&&(this.orderId=yield this.createOrder()),!this.orderId)throw new Xr;const c=this.isPayPalVaultedInstrumentPaymentData(d)?this.prepareVaultedInstrumentPaymentPayload(s,this.orderId,d):this.preparePaymentPayload(s,this.orderId,d);try{yield this.paymentIntegrationService.submitOrder(o,t),yield this.paymentIntegrationService.submitPayment(c)}catch(e){if(function(e){var t;return pa(e)&&"offsite_redirect"===(null===(t=e.body.additional_action_required)||void 0===t?void 0:t.type)}(e)){const t=null===(i=null===(n=e.body.additional_action_required)||void 0===n?void 0:n.data)||void 0===i?void 0:i.redirect_url;return new Promise(()=>window.location.replace(t))}return this.isProviderError(e)&&(yield this.paypalIntegrationService.loadPayPalSdk(r.methodId),yield new Promise((e,t)=>{var n;this.paypalcommerce&&(null===(n=this.paypalButton)||void 0===n||n.close(),this.renderButton(r.methodId,this.paypalcommerce),this.handleError(new Error("INSTRUMENT_DECLINED"),a)),t()})),this.handleError(e,a),Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,n){const{instrumentId:i,shouldSetAsDefaultInstrument:r}=n,o=!this.isTrustedVaultingFlow(n);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:i}}}}}preparePaymentPayload(e,t,n){const{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=Bd(n)?n:{};return{methodId:e,paymentData:{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var n,i,r,o;const a=this.paypalIntegrationService.getPayPalSdkOrThrow(),s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:d}=s.initializationData||{},{checkoutPaymentButtonStyles:c}=d||{},{container:l,onError:u,onRenderButton:h,onValidate:p,submitForm:m}=t;if(!l)throw new vi('Unable to initialize payment because "container" argument is not provided.');const y=this.getSmartButtonContainerId(l);if(!document.getElementById(y))throw new vi(`Unable to initialize payment because element with id ${y} does not exist.`);const g=Object.assign(Object.assign({},this.isPaypalCommerceAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.paypalIntegrationService.getValidButtonStyle(c),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,p),onApprove:e=>this.handleApprove(e,m),onError:e=>this.handleError(e,u),onCancel:()=>this.toggleLoadingIndicator(!1)});this.paypalButton=a.Buttons(g),this.paypalButton.isEligible()&&(h&&"function"==typeof h&&h(),(null===(i=(n=this.paypalButton).hasReturned)||void 0===i?void 0:i.call(n))&&this.isPaypalCommerceAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return Qh(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return Qh(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.paypalIntegrationService.createOrder("paypalcommercecheckout",{shouldSaveInstrument:(null==e?void 0:e.shouldSaveInstrument)||!1})})}getFieldsValues(){const{getFieldsValues:e}=this.paypalcommerce||{};return"function"==typeof e?e():void 0}isTrustedVaultingFlow(e){if(e&&Nd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e.instrumentId);return!(uc(n)&&!n.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&Nd(e)&&Bd(e)}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}isProviderError(e){var t,n,i;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(i=null===(n=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===n?void 0:n.provider_error)||void 0===i?void 0:i.code)}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}getSmartButtonContainerId(e){var t;return null!==(t=e.split("#")[1])&&void 0!==t?t:e}}const ep=fi(e=>new Xh(e,As(e),new ws(a()),new fd({containerStyles:Ka})),[{id:"paypalcommerce"}]);var tp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class np{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.loadingIndicator=n,this.payPalSdkScriptLoader=i}initialize(e){return tp(this,void 0,void 0,function*(){const{methodId:t,paypalcommerce:n,paypalcommercecredit:i}=e||{},r=i||n;if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const o=this.paymentIntegrationService.getState(),a=o.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:s=[],orderId:d}=a.initializationData||{},{bannerContainerId:c,container:l}=r;if(void 0!==c){if(!document.getElementById(c))return void console.error("Unable to create banner without valid banner container ID.");const e=s&&s.find(({id:e})=>"checkout"===e);if(!(null==e?void 0:e.status))return;const t=yield this.payPalSdkScriptLoader.getPayPalMessages(a,o.getCartOrThrow().currency.code,o.getLocale());return this.renderMessages(t,c,e)}d?this.orderId=d:(yield this.paypalIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==l?void 0:l.split("#")[1],this.renderButton(t,r))})}execute(e,t){return tp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);if(!this.orderId)throw new Xr;yield this.paymentIntegrationService.submitOrder(i,t),yield this.paypalIntegrationService.submitPayment(n.methodId,this.orderId)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){if(!(null==t?void 0:t.container))throw new vi('Unable to initialize payment because "container" argument is not provided.');const n=this.paypalIntegrationService.getPayPalSdkOrThrow(),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=i.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u=[n.FUNDING.PAYLATER,n.FUNDING.CREDIT];let h=!1;u.forEach(e=>{if(h)return;const t={fundingSource:e,style:this.paypalIntegrationService.getValidButtonStyle(o),createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercecreditcheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(t),this.paypalButton.isEligible()||e!==n.FUNDING.PAYLATER){if(!this.paypalButton.isEligible()&&e===n.FUNDING.CREDIT)throw new _i(`PayPal ${e} is not available for your region. Please use PayPal Checkout instead.`);d&&"function"==typeof d&&d(),this.paypalButton.render(a),h=!0}})}handleClick(e,t){return tp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;if(t&&"function"==typeof t)return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t&&"function"==typeof t&&t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}renderMessages(e,t,n){const i={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Zh(n)};e.Messages(i).render(`#${t}`)}}const ip=fi(e=>new np(e,As(e),new fd({containerStyles:Ka}),Cs()),[{id:"paypalcommercecredit"}]);var rp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class op{constructor(e,t,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=n}initialize(e){var t,n;return rp(this,void 0,void 0,function*(){const{methodId:i,paypalcommerce:r,paypalcommercevenmo:o}=e||{},a=o||r;if(!i)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!a)throw new vi('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);(null===(t=s.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(n=s.initializationData)||void 0===n?void 0:n.orderId:(yield this.paypalCommerceIntegrationService.loadPayPalSdk(i),this.loadingIndicatorContainer=a.container.split("#")[1],this.renderButton(i,a))})}execute(e,t){return rp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);if(!this.orderId)throw new Xr;yield this.paymentIntegrationService.submitOrder(i,t),yield this.paypalCommerceIntegrationService.submitPayment(n.methodId,this.orderId)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){const n=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=i.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u={fundingSource:n.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o),createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmocheckout"),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onCancel:()=>this.toggleLoadingIndicator(!1),onError:e=>this.handleError(e,s)};if(this.paypalButton=n.Buttons(u),!this.paypalButton.isEligible())throw new _i("PayPal Venmo is not available for your region. Please use PayPal Checkout instead.");d&&"function"==typeof d&&d(),this.paypalButton.render(a)}handleClick(e,t){return rp(this,void 0,void 0,function*(){const{resolve:n,reject:i}=e;return t(()=>(this.toggleLoadingIndicator(!0),n()),i)})}handleApprove({orderID:e},t){this.orderId=e,t(),this.toggleLoadingIndicator(!1)}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const ap=fi(e=>new op(e,$s(e),new fd({styles:{backgroundColor:"black"}})),[{id:"paypalcommercevenmo"}]),sp={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};var dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cp{constructor(e,t,n,i,r=3e3,o=3e5){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalSdkScriptLoader=n,this.loadingIndicator=i,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=ce,this.isOrderApprovedProcessing=!1}initialize(e){return dp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerce:i,paypalcommercealternativemethods:r}=e,o=r||i;if(this.paypalcommercealternativemethods=r,!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!o)throw new vi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');const a=this.paymentIntegrationService.getState(),s=a.getPaymentMethodOrThrow(n,t),{orderId:d,shouldRenderFields:c}=s.initializationData||{},l=a.getStoreConfigOrThrow().checkoutSettings.features;this.isOrderApprovedProcessing=Ci(l,"PAYPAL-5431.order_approved_processing",!1),d?this.orderId=d:(this.paypalApms=yield this.paypalSdkScriptLoader.getPayPalApmsSdk(s,a.getCartOrThrow().currency.code,a.getLocale()),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(n,t,o),c&&this.renderFields(n,o))})}execute(e,t){return dp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{methodId:r,gatewayId:o}=n;if(!this.orderId)throw new Xr;this.isOrderApprovedProcessing||"ideal"!==r||(yield new Promise((e,t)=>{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)&&(r!==js.IDEAL||this.isOrderApprovedProcessing)||(yield this.paymentIntegrationService.submitOrder(i,t)),yield this.paypalCommerceIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;return this.orderId=void 0,this.isOrderApprovedProcessing||this.resetPollingMechanism(),null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,n,i){return dp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceIntegrationService.getOrderStatus(null!=i?i:"paypalcommerce"),o=r===Bs.Approved,a=r===Bs.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,n,i);yield this.reinitializeStrategy({methodId:e,gatewayId:i,paypalcommercealternativemethods:this.paypalcommercealternativemethods}),this.handleError(new wc)}catch(e){n()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}reinitializeStrategy(e){return dp(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}handleError(e){const{onError:t}=this.paypalcommercealternativemethods||{};this.isOrderApprovedProcessing||this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderButton(e,t,n){const i=this.getPaypalAmpsSdkOrThrow(),r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t),{buttonStyle:o}=r.initializationData||{},{container:a,onError:s,onRenderButton:d,submitForm:c}=n,l={fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o),onInit:(e,t)=>n.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,n),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deinitializePollingMechanism()},onError:e=>{this.deinitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>dp(this,void 0,void 0,function*(){return n.onValidate(t.resolve,t.reject)})};this.paypalButton=i.Buttons(l),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}onCreateOrder(e,t,n){var i;return dp(this,void 0,void 0,function*(){const{onValidate:r}=n;yield r(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),ce);const o=yield this.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethodscheckout");if(this.isNonInstantPaymentMethod(e)&&(e===js.IDEAL&&this.isOrderApprovedProcessing||e===js.OXXO)){const n={useStoreCredit:!1},r={params:{methodId:e,gatewayId:t}};if(yield this.paymentIntegrationService.submitOrder(n,r),e===js.IDEAL){const t=this.paymentIntegrationService.getState(),n=null===(i=t.getOrder())||void 0===i?void 0:i.orderId;yield this.paypalCommerceIntegrationService.updateOrder("paypalcommercealternativemethods",e,n)}yield this.paypalCommerceIntegrationService.submitPayment(e,o,t)}return o})}handleApprove({orderID:e},t){this.orderId=e,t()}handleFailure(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderFields(e,t){const n=this.getPaypalAmpsSdkOrThrow(),i=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=i.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new vi('Unable to initialize payment because "options.paypalcommercealternativemethods" argument should contain "apmFieldsContainer".');const c=document.querySelector(s);c&&(c.innerHTML="");const l={fundingSource:e,style:d||{},fields:{name:{value:`${r} ${o}`},email:{value:a}}};n.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in js}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new mi;return this.paypalApms}}const lp=fi(e=>new cp(e,As(e),Cs(),new fd({containerStyles:sp})),[{gateway:"paypalcommercealternativemethods"}]);var up=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hp{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){return up(this,void 0,void 0,function*(){const{methodId:t,paypalcommercecreditcards:n,paypalcommerce:i}=e,r=n||i,{form:o,onCreditCardFieldsRenderingError:a,onLoadComplete:s}=r||{};if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new vi('Unable to proceed because "options.paypalcommercecreditcards.form" argument is not provided.');this.hostedFormOptions=o,this.isCreditCardForm=Ac(o.fields),this.isCreditCardVaultedForm=Tc(o.fields)&&!this.hasUndefinedValues(),yield this.paymentIntegrationService.loadPaymentMethod(t),yield this.paypalIntegrationService.loadPayPalSdk(t,void 0,!0,!0),(this.isCreditCardForm||this.isCreditCardVaultedForm)&&(yield this.initializeFields(o,a)),null==s||s(),this.shouldInitializePayPalFastlane(t)&&(yield this.initializePayPalFastlaneOrThrow(t))})}execute(e,t){return up(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{methodId:r,paymentData:o}=n||{};if(!n||!r)throw new co(["payment"]);if(this.executionPaymentData=o,this.isCreditCardForm||this.isCreditCardVaultedForm)yield this.validateHostedFormOrThrow(),yield this.submitHostedForm();else{const{orderId:e}=yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",this.getInstrumentParams());this.returnedOrderId=e}const a=this.preparePaymentPayload(r,o,this.returnedOrderId,this.returnedVaultedToken);yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e,t,n,i;return up(this,void 0,void 0,function*(){return yield null===(e=this.cvvField)||void 0===e?void 0:e.close(),yield null===(t=this.expiryField)||void 0===t?void 0:t.close(),yield null===(n=this.numberField)||void 0===n?void 0:n.close(),yield null===(i=this.nameField)||void 0===i?void 0:i.close(),Promise.resolve()})}preparePaymentPayload(e,t,n,i){const{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=Bd(t)?t:{},a=t&&Nd(t)?t.instrumentId:void 0,s=ue({verification_nonce:i,token:a},J);return{methodId:e,paymentData:{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o,instrumentId:a,formattedPayload:Object.assign(Object.assign({},i||a?{bigpay_token:s}:{}),n?{card_with_order:{order_id:n}}:{})}}}initializeFields(e,t){return up(this,void 0,void 0,function*(){const{fields:n,styles:i}=e,r=this.paypalIntegrationService.getPayPalSdkOrThrow(),o=this.getExecuteCallback(n),a=Object.assign({style:this.getInputStyles(i),onApprove:({orderID:e,vaultSetupToken:t,liabilityShift:n})=>{if(n===xs.No||n===xs.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Qr},inputEvents:{onChange:t=>this.onChangeHandler(e,t),onFocus:t=>this.onFocusHandler(e,t),onBlur:t=>this.onBlurHandler(e,t),onInputSubmitRequest:t=>this.onInputSubmitRequest(e,t)}},o);if(this.cardFields=yield r.CardFields(a),!this.cardFields.isEligible())throw new ri(ti.PaymentNotInitialized);try{this.stylizeInputContainers(n),Ac(n)&&(yield this.renderFields(n)),Tc(n)&&(yield this.renderVaultedFields(n))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return Tc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>up(this,void 0,void 0,function*(){const{setupToken:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",Object.assign(Object.assign({},this.getInstrumentParams()),{setupToken:!0})))||{};return e})}}createOrderCallback(){return{createOrder:()=>up(this,void 0,void 0,function*(){const{orderId:e}=(yield this.paypalIntegrationService.createOrderCardFields("paypalcommercecreditcardscheckout",this.getInstrumentParams()))||{};return e})}}handleApprove({orderID:e,vaultSetupToken:t}){e&&(this.returnedOrderId=e),t&&(this.returnedVaultedToken=t)}renderFields(e){var t,n,i,r;return up(this,void 0,void 0,function*(){const o=this.getCardFieldsOrThrow();(null===(t=e.cardCode)||void 0===t?void 0:t.containerId)&&(this.cvvField=o.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCode.containerId}`)),(null===(n=e.cardExpiry)||void 0===n?void 0:n.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(i=e.cardName)||void 0===i?void 0:i.containerId)&&(this.nameField=o.NameField({placeholder:""}),yield this.nameField.render(`#${e.cardName.containerId}`)),(null===(r=e.cardNumber)||void 0===r?void 0:r.containerId)&&(this.numberField=o.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumber.containerId}`))})}renderVaultedFields(e){var t,n,i;return up(this,void 0,void 0,function*(){const r=this.getCardFieldsOrThrow();(null===(t=e.cardCodeVerification)||void 0===t?void 0:t.containerId)&&(this.cvvField=r.CVVField({placeholder:""}),yield this.cvvField.render(`#${e.cardCodeVerification.containerId}`)),(null===(n=e.cardExpiryVerification)||void 0===n?void 0:n.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(i=e.cardNumberVerification)||void 0===i?void 0:i.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(Bd(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(Nd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return up(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n={billingAddress:{company:t.company,addressLine1:t.address1,addressLine2:t.address2,adminArea1:t.stateOrProvinceCode,adminArea2:t.city,postalCode:t.postalCode,countryCode:t.countryCode}};try{this.isCreditCardVaultedForm?yield e.submit():yield e.submit(n)}catch(e){throw new Qr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return up(this,void 0,void 0,function*(){const n=this.getCardFieldsOrThrow(),i=yield n.getState().then(e=>e),r=this.getValidityData(i);if(!r.isValid)throw null===(t=null===(e=this.hostedFormOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,r),new lo(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const n=Object.keys(t);return{isValid:n.every(e=>{var n;return null===(n=t[e])||void 0===n?void 0:n.isValid}),errors:n.reduce((e,n)=>{var i;const r=this.mapFieldType(n);return Object.assign(Object.assign({},e),{[r]:(null===(i=t[n])||void 0===i?void 0:i.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case Ec.CardCode:case Ec.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case Ec.CardNumber:case Ec.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case Ec.CardExpiry:case Ec.CardExpiryVerification:return{fieldType:e,message:"Invalid card expiry",type:"invalid_card_expiry"};default:return{fieldType:e,message:"Invalid field",type:"invalid"}}}mapValidationErrors(e={}){const t={};return Object.keys(e).forEach(n=>{var i,r;t[n]=[{message:(null===(r=null===(i=e[n])||void 0===i?void 0:i[0])||void 0===r?void 0:r.message)||"",type:n}]}),t}mapFieldType(e){switch(e){case"name":return Ec.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?Ec.CardNumber:Ec.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?Ec.CardExpiry:Ec.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?Ec.CardCode:Ec.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new ri(ti.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,n,i;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontWeight)||"400",outline:"none",padding:"9px 13px"},o=Object.assign(Object.assign({},r),{color:"#333333"});return{input:o,".invalid":Object.assign(Object.assign({},r),{color:"red"}),".valid":o,":focus":o}}stylizeInputContainers(e){Object.values(e||{}).forEach(e=>{const t=document.getElementById(`${(null==e?void 0:e.containerId)||""}`);t&&(t.style.padding="0px",t.style.boxShadow="none",t.style.border="none",t.style.background="transparent",t.style.marginBottom="10px",t.style.marginLeft="-5px")})}hasUndefinedValues(){return!this.hostedFormOptions||Object.values(this.hostedFormOptions.fields).some(e=>void 0===e)}onChangeHandler(e,t){var n;null===(n=null==e?void 0:e.onValidate)||void 0===n||n.call(e,this.getValidityData(t))}onFocusHandler(e,t){var n;null===(n=null==e?void 0:e.onFocus)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var n;null===(n=null==e?void 0:e.onBlur)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var n;null===(n=null==e?void 0:e.onEnter)||void 0===n||n.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,n;const i=this.paymentIntegrationService.getState(),r=i.getPaymentMethodOrThrow(e),o=i.getPaymentProviderCustomer(),a=(s=o)&&("authenticationState"in s||"addresses"in s||"instruments"in s)?o:{};var s;return(null===(t=null==r?void 0:r.initializationData)||void 0===t?void 0:t.isAcceleratedCheckoutEnabled)&&(null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.isPayPalCommerceAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return up(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getPaymentMethodOrThrow(e),{initializationData:r}=i;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(i,n.currency.code,n.id,t.getLocale());yield this.paypalFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const pp=fi(e=>new hp(e,As(e),Cs(),nd()),[{id:"paypalcommercecreditcards"}]);var mp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class yp{constructor(e,t,n,i=3e3,r=3e5){this.paymentIntegrationService=e,this.paypalCommerceService=t,this.loadingIndicator=n,this.pollingInterval=i,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=ce}initialize(e){return mp(this,void 0,void 0,function*(){const{gatewayId:t,methodId:n,paypalcommerceratepay:i}=e;if(!n)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new vi('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!i)throw new vi('Unable to initialize payment because "options.paypalcommerceratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=i;if(!o)throw new vi('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new vi('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{merchantId:d}=s.initializationData||{};if(!d)throw new vi("Unable to initialize payment because merchantId argument is not provided.");this.paypalcommerceratepay=i,yield this.paypalCommerceService.loadPayPalSdk(n),this.createFraudNetScript(d,n,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return mp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{getFieldsValues:r}=this.paypalcommerceratepay||{};if(!n)throw new co(["payment"]);if(!r||"function"!=typeof r)throw new vi('Unable to initialize payment because "options.getFieldsValues" argument is not provided.');this.toggleLoadingIndicator(!0);try{const e=yield this.paypalCommerceService.createOrder("paypalcommercealternativemethodscheckout",{metadataId:this.guid}),{ratepayBirthDate:o,ratepayPhoneNumber:a,ratepayPhoneCountryCode:s}=r(),d={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:n.methodId,rate_pay:{birth_date:this.normalizeDate(o),phone:{national_number:a,country_code:s.split("+")[1]}},paypal_account:{order_id:e}}};return yield this.paymentIntegrationService.submitOrder(i,t),yield this.paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:d}),yield new Promise((e,t)=>{this.initializePollingMechanism(n.methodId,e,t,n.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new Cd)}deinitialize(){const{legalTextContainer:e}=this.paypalcommerceratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],n=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),n.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),n=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${n}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const n=e,i=t.split("#")[1],r=document.getElementById(i),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",n),null==o||o.prepend(a);const s=this.paypalCommerceService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(n))throw new vi('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${n}`)}handleError(e){const{onError:t}=this.paypalcommerceratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,n){const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{testMode:r}=i.config,o=document.createElement("script");o.setAttribute("type","application/json"),o.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),o.setAttribute("data-id","fraudnetScript"),this.guid=this.generateGUID();const a={f:this.guid,s:`${e}_checkout-page`,sandbox:r};o.innerHTML=JSON.stringify(a),document.body.appendChild(o)}generateGUID(){let e="";for(let t=0;t<32;t+=1)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())];return e}loadFraudnetConfig(){const e=document.createElement("script");e.setAttribute("data-id","fraudnetConfig"),e.src="https://c.paypal.com/da/r/fb.js",document.body.appendChild(e)}reinitializeStrategy(e){return mp(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,n,i){return mp(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const n=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(n),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceService.getOrderStatus("paypalcommercealternativemethods",{params:{useMetadata:!0}}),o=r===Ss.PollingStop,a=r===Ss.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return n();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,n,i);yield this.reinitializeStrategy({methodId:e,gatewayId:i,paypalcommerceratepay:this.paypalcommerceratepay}),this.handleError(new wc)}catch(e){this.handleError(e),n()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const gp=fi(e=>new yp(e,As(e),new fd({containerStyles:Object.assign(Object.assign({},Ka),{position:"fixed"})})),[{gateway:"paypalcommercealternativemethods",id:"ratepay"}]);function fp(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var vp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _p{constructor(e,t,n,i){this.paymentIntegrationService=e,this.paypalCommerceRequestSender=t,this.paypalSdkScriptLoader=n,this.paypalFastlaneUtils=i}initialize(e){var t,n;return vp(this,void 0,void 0,function*(){const{methodId:i,paypalcommercefastlane:r}=e;if(this.methodId=i,this.paypalcommercefastlane=r,!i)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new vi('Unable to initialize payment because "options.paypalcommercefastlane" argument is not provided.');if(!r.onInit||"function"!=typeof r.onInit)throw new vi('Unable to initialize payment because "options.paypalcommercefastlane.onInit" argument is not provided or it is not a function.');if(!r.onChange||"function"!=typeof r.onChange)throw new vi('Unable to initialize payment because "options.paypalcommercefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(i),{isDeveloperModeApplicable:d,isFastlaneStylingEnabled:c}=s.initializationData||{};this.threeDSVerificationMethod=null===(t=s.initializationData)||void 0===t?void 0:t.threeDSVerificationMethod,this.paypalFastlaneSdk=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(s,a.currency.code,a.id,o.getLocale());const l=rd(c?null===(n=null==s?void 0:s.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},null==r?void 0:r.styles);yield this.paypalFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(i)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(i))})}execute(e,t){return vp(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{paymentData:r,methodId:o}=n,a=r&&Nd(r);try{yield this.paymentIntegrationService.submitOrder(i,t);const e=a?yield this.prepareVaultedInstrumentPaymentPayload(o,r):yield this.preparePaymentPayload(o,r);yield this.paymentIntegrationService.submitPayment(e),this.paypalFastlaneUtils.removeStorageSessionId()}catch(e){if(function(e){return"object"==typeof e&&null!==e&&"message"in e&&"response"in e&&"body"in e.response&&"name"in e.response.body}(e)&&"INVALID_REQUEST"===e.response.body.name){const e={translationKey:"payment.errors.invalid_request_error"};return this.handleError(e),Promise.reject()}if(e instanceof Error&&"FastlaneError"!==e.name)throw e;return Promise.reject()}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return vp(this,void 0,void 0,function*(){return Promise.resolve()})}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getCustomerOrThrow(),i=e.getPaymentProviderCustomer(),r=fp(i)?i:{},o=this.paypalFastlaneUtils.getStorageSessionId();return!(!n.isGuest||(null==r?void 0:r.authenticationState)===vs.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}runPayPalAuthenticationFlowOrThrow(e){return vp(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),n=t.getCartOrThrow(),i=t.getCustomer(),r=t.getBillingAddress(),o=(null==i?void 0:i.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.paypalFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(a),{authenticationState:d,addresses:c,instruments:l}=this.paypalFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,s);yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:d,addresses:c,instruments:l}),s.authenticationState===vs.CANCELED?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(n.id)}catch(e){}})}initializePayPalPaymentComponent(){return vp(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),t=e.phone,n=`${e.firstName} ${e.lastName}`.trim(),i=this.paypalFastlaneUtils.getPayPalFastlaneOrThrow(),r={fields:Object.assign({cardholderName:{prefill:n,enabled:!0}},t&&{phoneNumber:{prefill:t}})};this.paypalComponentMethods=yield i.FastlaneCardComponent(r)})}renderPayPalPaymentComponent(e){const t=this.getPayPalComponentMethodsOrThrow();if(!e)throw new vi('Unable to render card component because "container" argument is not provided.');t.render(e)}getPayPalComponentMethodsOrThrow(){if(!this.paypalComponentMethods)throw new mi;return this.paypalComponentMethods}prepareVaultedInstrumentPaymentPayload(e,t){return vp(this,void 0,void 0,function*(){const{instrumentId:n}=t,i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).config.is3dsEnabled?yield this.get3DSNonce(n):n;return yield this.createOrder(i),{methodId:e,paymentData:{formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:i}}}}})}preparePaymentPayload(e,t){return vp(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getBillingAddressOrThrow(),r=n.getPaymentMethodOrThrow(e),o=`${i.firstName} ${i.lastName}`.trim(),{getPaymentToken:a}=this.getPayPalComponentMethodsOrThrow(),{id:s}=yield a({name:{fullName:o},billingAddress:this.paypalFastlaneUtils.mapBcToPayPalAddress(i)}),d=r.config.is3dsEnabled?yield this.get3DSNonce(s):s;yield this.createOrder(d);const{shouldSaveInstrument:c=!1,shouldSetAsDefaultInstrument:l=!1}=Bd(t)?t:{};return{methodId:e,paymentData:Object.assign(Object.assign({},t),{shouldSaveInstrument:c,shouldSetAsDefaultInstrument:l,formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:d}}})}})}createOrder(e){return vp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getCartOrThrow().id;if(this.methodId){const{orderId:n}=yield this.paypalCommerceRequestSender.createOrder(this.methodId,{cartId:t,fastlaneToken:e});this.orderId=n}})}get3DSNonce(e){var t;return vp(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),i=n.getCartOrThrow(),r=n.getOrderOrThrow(),o=n.getStoreConfigOrThrow().links.checkoutLink,a=null===(t=this.paypalFastlaneSdk)||void 0===t?void 0:t.ThreeDomainSecureClient;if(!a)throw new mi;const s={amount:r.orderAmount.toFixed(2),currency:i.currency.code,nonce:e,threeDSRequested:this.threeDSVerificationMethod===hs.Always,transactionContext:{experience_context:{locale:"en-US",return_url:o,cancel_url:o}}},d=yield a.isEligible(s);if(this.threeDSVerificationMethod===hs.Always&&!d)throw new Xr;if(d){const{liabilityShift:e,authenticationState:t,nonce:n}=yield a.show();if(e===xs.No||e===xs.Unknown||t===ps.Errored||t===ps.Cancelled)throw new Xr;if(t===ps.Succeeded&&[xs.Yes,xs.Possible].includes(e))return n;throw new Xr}return e})}handlePayPalStoredInstrumentChange(e){return vp(this,void 0,void 0,function*(){const t=this.paypalFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:n,selectedCard:i}=yield t.profile.showCardSelector();if(n){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),n=fp(t)?t:{},r=this.paypalFastlaneUtils.mapPayPalToBcInstrument(e,i)[0];return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},n),{instruments:[r]})),r}})}handleError(e){var t;(null===(t=this.paypalcommercefastlane)||void 0===t?void 0:t.onError)&&"function"==typeof this.paypalcommercefastlane.onError&&this.paypalcommercefastlane.onError(e)}}const Sp=fi(e=>{const{getHost:t}=e.getState();return new _p(e,new Gs(n({host:t()})),Cs(),nd())},[{id:"paypalcommerceacceleratedcheckout"}]);var Ip,wp,Cp,bp,Pp,Op;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(Ip||(Ip={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(wp||(wp={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(Cp||(Cp={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(bp||(bp={})),function(e){e.PILL="pill",e.RECT="rect"}(Pp||(Pp={})),function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(Op||(Op={}));var Ep=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Ap{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.useRedirectFlow=!1,this.window=window}initialize(e){return Ep(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();this.paymentMethod=t.getPaymentMethodOrThrow(e.methodId),this.useRedirectFlow=!0===(e.paypalexpress&&e.paypalexpress.useRedirectFlow);const n=this.paymentMethod.config.merchantId;if(!this.isInContextEnabled()||!n)throw new ni(ei.MissingPaymentMethod);const i=yield this.scriptLoader.loadPaypalSDK();this.paypalSdk=i,this.paypalSdk.checkout.setup(n,{button:"paypal-button",environment:this.paymentMethod.config.testMode?"sandbox":"production"})})}deinitialize(){return this.isInContextEnabled()&&this.paypalSdk&&(this.paypalSdk.checkout.closeFlow(),this.paypalSdk=void 0),Promise.resolve()}execute(e,t){return Ep(this,void 0,void 0,function*(){let n,i;const r=this.paypalSdk;if(!this.isAcknowledgedOrFinalized()){if(!this.isInContextEnabled()||this.useRedirectFlow)return n=yield this.paymentIntegrationService.submitOrder(e,t),i=n.getPaymentRedirectUrl(),i&&this.window.top&&(this.window.top.location.href=i),new Promise(ce);if(!r)throw new ri(ti.PaymentNotInitialized);r.checkout.initXO();try{n=yield this.paymentIntegrationService.submitOrder(e,t)}catch(e){return r.checkout.closeFlow(),Promise.reject(e)}return i=n.getPaymentRedirectUrl(),i&&r.checkout.startFlow(i),new Promise(ce)}yield this.paymentIntegrationService.submitOrder(e,t)})}finalize(e){return Ep(this,void 0,void 0,function*(){return this.paymentIntegrationService.getState().getOrder()&&this.isAcknowledgedOrFinalized()?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new Cd)})}isAcknowledgedOrFinalized(){const e=this.paymentIntegrationService.getState();return e.getPaymentStatus()===Op.ACKNOWLEDGE||e.getPaymentStatus()===Op.FINALIZE}isInContextEnabled(){return!(!this.paymentMethod||!this.paymentMethod.config.merchantId)}}class Tp{constructor(e){this.scriptLoader=e,this.window=window}loadPaypalSDK(e=""){return t=this,n=void 0,r=function*(){const t=Object.assign({async:!0,attributes:{"data-merchant-id":e}},e&&{attributes:{"data-merchant-id":e}});if(yield this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",t),!this.window.paypal)throw new mi;return this.window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const kp=fi(e=>new Ap(e,new Tp(a())),[{id:"paypalexpress",type:"PAYMENT_TYPE_HOSTED"},{id:"paypalexpresscredit",type:"PAYMENT_TYPE_HOSTED"}]);var Dp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Mp extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this.threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Dp(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);n.config.is3dsEnabled&&(yield this.threeDSecureFlow.prepare(n))})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Dp(this,void 0,void 0,function*(){const{payment:{methodId:i=""}={}}=e,r=this.paymentIntegrationService.getState();return r.getPaymentStatus()===dl.ACKNOWLEDGE?(yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:{methodId:i}}),t),Promise.resolve()):r.getPaymentMethodOrThrow(i).config.is3dsEnabled?this.threeDSecureFlow.start(n.execute.bind(this),e,t,this._hostedForm):n.execute.call(this,e,t)})}}const zp=fi(e=>new Mp(e,new Au(e,new Fu(new Lu(a())))),[{id:"paypal"}]);class xp extends tu{constructor(e,t){super(e),this.paymentIntegrationService=e,this._formPoster=t}execute(e,t){const{payment:n}=e;if(!n)throw new ri(ti.PaymentNotInitialized);const{paymentData:i}=n;if(!i)throw new ni(ei.MissingPayment);if(this._isThreeDSTwoExperimentOn()){const t=Object.assign(Object.assign({},i),{browser_info:ss()});e.payment&&(e.payment.paymentData=t)}return super.execute(e,t).catch(e=>pa(e)&&fe(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{let t;t=this._isThreeDSTwoExperimentOn()&&!e.body.three_ds_result.merchant_data?{creq:e.body.three_ds_result.payer_auth_request}:{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data},this._formPoster.postForm(e.body.three_ds_result.acs_url,t,void 0,"_top")}):Promise.reject(e))}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===dl.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),super.finalize()}_isThreeDSTwoExperimentOn(){return!0===this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features["INT-4994.Opayo_3DS2"]}}const Np=fi(e=>new xp(e,Ee()),[{id:"sagepay"}]);class Rp{constructor(e,t){this._formPoster=e,this._paymentIntegrationService=t}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new co(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(i,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))}catch(e){if(!pa(e)||"object"!=typeof(o=e.body)||null===o||!("additional_action_required"in o)||!this._isAdditionalActionRequired(e.body))return Promise.reject(e);const{body:{additional_action_required:{data:{redirect_url:t}}}}=e;return new Promise(()=>{this.redirectUrl(t)})}var o},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}redirectUrl(e){return this._formPoster.postForm(e,{})}_isAdditionalActionRequired(e){const{additional_action_required:t,status:n}=e;return"additional_action_required"===n&&t&&"offsite_redirect"===t.type}}class Fp extends Rp{redirectUrl(e){window.location.replace(e)}}const Lp=fi(e=>new Fp(Ee(),e),[{id:"sezzle"}]);var jp;!function(e){e.CHARGE="CHARGE",e.STORE="STORE"}(jp||(jp={}));var Bp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Up{constructor(e,t){this._scriptLoader=e,this._paymentIntegrationService=t}initialize({testMode:e,applicationId:t,locationId:n}){return Bp(this,void 0,void 0,function*(){const i=yield this._scriptLoader.load(e);this._payments=i.payments(t,n)})}deinitialize(){return Bp(this,void 0,void 0,function*(){this._formValidationSubscription&&this._formValidationSubscription.unsubscribe(),this._card&&(yield this._card.destroy()),this._formValidationSubscription=void 0,this._card=void 0,this._payments=void 0})}initializeCard({containerId:e,style:t,onValidationChange:n}){return Bp(this,void 0,void 0,function*(){const{postalCode:i}=this._paymentIntegrationService.getState().getBillingAddress()||{};this._card=yield this._getPayments().card(),yield this._card.attach(`#${e}`);try{yield this._card.configure({postalCode:i,style:t})}catch(e){}n&&(this._formValidationSubscription=this._subscribeToFormValidation(this._card,n))})}tokenize(){return Bp(this,void 0,void 0,function*(){const e=yield this._getCard().tokenize();if("OK"!==e.status||!e.token){let t=`Tokenization failed with status: ${e.status}`;throw e.errors&&(t+=` and errors: ${JSON.stringify(e.errors)}`),new Sh("payment.errors.card_error","SquareV2TokenizationError",t)}return e.token})}verifyBuyer(e,t){return Bp(this,void 0,void 0,function*(){return t===jp.CHARGE?this._chargeVerifyBuyer(e):this._storeVerifyBuyer(e)})}_getPayments(){return ii(this._payments,()=>new ri(ti.PaymentNotInitialized))}_subscribeToFormValidation(e,t){const n=["cardNumber","cvv"],i=new Set(n),r=["focusClassAdded","focusClassRemoved","errorClassAdded","errorClassRemoved","cardBrandChanged","postalCodeChanged"].map(t=>S(e,t));return I(...r).pipe(T(e=>{const{detail:{field:t,currentState:{isCompletelyValid:r}}}=e;return n.includes(t)&&i[r?"delete":"add"](t),0===i.size}),E()).subscribe(t)}_getCard(){return ii(this._card,()=>new ri(ti.PaymentNotInitialized))}_mapToSquareBillingContact({firstName:e,lastName:t,address1:n,address2:i,city:r,stateOrProvinceCode:o,postalCode:a,countryCode:s,email:d,phone:c}){return{givenName:e,familyName:t,addressLines:[n,i],city:r,state:o,postalCode:a,countryCode:s,email:d,phone:c}}_chargeVerifyBuyer(e){return Bp(this,void 0,void 0,function*(){const{getCheckoutOrThrow:t,getBillingAddressOrThrow:n}=this._paymentIntegrationService.getState(),{outstandingBalance:i,cart:r}=t(),o={amount:i.toString(),billingContact:this._mapToSquareBillingContact(n()),currencyCode:r.currency.code,intent:jp.CHARGE},a=yield this._getPayments().verifyBuyer(e,o);return a?a.token:""})}_storeVerifyBuyer(e){return Bp(this,void 0,void 0,function*(){const{getBillingAddressOrThrow:t}=this._paymentIntegrationService.getState(),n={billingContact:this._mapToSquareBillingContact(t()),intent:jp.STORE},i=yield this._getPayments().verifyBuyer(e,n);return i?i.token:""})}}var qp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Vp{constructor(e,t){this._paymentIntegrationService=e,this._squareV2PaymentProcessor=t}initialize(e){var t;return qp(this,void 0,void 0,function*(){if(!(null===(t=null==e?void 0:e.squarev2)||void 0===t?void 0:t.containerId))throw new vi('Unable to proceed because "containerId" argument is not provided.');const{methodId:n,squarev2:i}=e,{config:{testMode:r},initializationData:o}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{applicationId:a,locationId:s}=o||{};if(!a)throw new Xr;yield this._squareV2PaymentProcessor.initialize({applicationId:a,locationId:s,testMode:r}),yield this._squareV2PaymentProcessor.initializeCard(i)})}execute({payment:e}){return qp(this,void 0,void 0,function*(){if(!e)throw new co(["payment"]);const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r}=Bd(n)?n:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};yield this._paymentIntegrationService.submitOrder();const o=n&&Nd(n)?yield this._getVaultedInstrumentPayload(t,n):yield this._getCardPayload(t,i);yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:Object.assign(Object.assign({},o),{vault_payment_instrument:i||!1,set_as_default_stored_instrument:r||!1})}}))})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this._squareV2PaymentProcessor.deinitialize()}shouldVerify(){const{features:e}=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings;return e["PROJECT-3828.add_3ds_support_on_squarev2"]}_getCardPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),r=yield this._squareV2PaymentProcessor.tokenize();if(i&&"isSquareV2ApiV2Enabled"in i?!i.isSquareV2ApiV2Enabled:!this.shouldVerify())return{credit_card_token:{token:r}};let o={nonce:r,token:yield this._squareV2PaymentProcessor.verifyBuyer(r,jp.CHARGE)};if(t){const e=yield this._squareV2PaymentProcessor.tokenize();o=Object.assign(Object.assign({},o),{store_card_nonce:e,store_card_token:yield this._squareV2PaymentProcessor.verifyBuyer(e,jp.STORE)})}return{credit_card_token:{token:JSON.stringify(o)}}})}_getVaultedInstrumentPayload(e,t){return qp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:n}=this._paymentIntegrationService.getState(),{initializationData:i}=n(e),{instrumentId:r}=t,o=(i&&"isSquareV2ApiV2Enabled"in i?i.isSquareV2ApiV2Enabled:this.shouldVerify())?yield this._squareV2PaymentProcessor.verifyBuyer(yield this._getSquareCardIdOrThrow(e,r),jp.CHARGE):void 0;return{bigpay_token:Object.assign({token:r},o&&{three_d_secure:{token:o}})}})}_getSquareCardIdOrThrow(e,t){return qp(this,void 0,void 0,function*(){const n=yield this._paymentIntegrationService.loadPaymentMethod(e,{params:{method:e,bigpayToken:t}}),{initializationData:i}=n.getPaymentMethodOrThrow(e),{cardId:r}=i||{};if(!r)throw new co(["cardId"]);return r})}}var Gp;!function(e){e.LIVE="https://web.squarecdn.com/v1/square.js",e.SANDBOX="https://sandbox.web.squarecdn.com/v1/square.js"}(Gp||(Gp={}));class Hp{constructor(e){this._scriptLoader=e}load(e=!1){return t=this,n=void 0,r=function*(){return yield this._scriptLoader.loadScript(e?Gp.SANDBOX:Gp.LIVE),function(e){if(!function(e){return"Square"in e}(e))throw new mi}(window),window.Square},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}const Wp=fi(e=>new Vp(e,new Up(new Hp(a()),e)),[{id:"squarev2"}]);function $p(e){return null!==e&&"object"==typeof e&&"cardNumberElementOptions"in e&&"cardCvcElementOptions"in e&&"cardExpiryElementOptions"in e&&void 0!==e.cardNumberElementOptions&&void 0!==e.cardCvcElementOptions&&void 0!==e.cardExpiryElementOptions}var Yp,Kp,Jp,Zp;!function(e){e.Solid="solid",e.Default="default"}(Yp||(Yp={})),function(e){e.Alipay="alipay",e.CardCvc="cardCvc",e.CardExpiry="cardExpiry",e.CardNumber="cardNumber",e.CreditCard="card",e.IDEAL="idealBank",e.Sepa="iban"}(Kp||(Kp={})),function(e){e.Alipay="alipay",e.CreditCard="card",e.IDEAL="ideal",e.Sepa="sepa_debit"}(Jp||(Jp={})),function(e){e.AuthFailure="auth_failure"}(Zp||(Zp={}));class Qp extends Xn{constructor(e){super(e===Zp.AuthFailure?"User did not authenticate":"There was an error while processing your payment. Please try again or contact us."),this.type="stripev3_error",this.subtype=e}}var Xp=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const em=[Kp.Alipay,Kp.IDEAL];class tm{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Xp(this,void 0,void 0,function*(){const{stripev3:t,methodId:n,gatewayId:i}=e;if(!i)throw new vi('Unable to initialize payment because "gatewayId" argument is not provided.');this.initializeOptions=t,this.isDeinitialize=!1;const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{initializationData:{stripePublishableKey:o,stripeConnectedAccount:a,useIndividualCardFields:s,allowRedisplayForStoredInstruments:d}}=r;this._allowRedisplayForStoredInstruments=d;const c=this.getInitializeOptions().form;this.useIndividualCardFields=s,this.stripeV3Client=yield this.loadStripeJs(o,a),this.isCreditCard(n)&&this.shouldShowTSVHostedForm(n,i)&&c?this.hostedForm=yield this.mountCardVerificationFields(c):this.stripeElement=yield this.mountCardFields(n)})}execute(e,t){var n,i;return Xp(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);let a,s;if(!r||!r.paymentData)throw new co(["payment.paymentData"]);const{paymentData:d,gatewayId:c,methodId:l}=r,{shouldSaveInstrument:u,shouldSetAsDefaultInstrument:h}=Bd(d)?d:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},p=H(em,l),{isStoreCreditApplied:m}=this.paymentIntegrationService.getState().getCheckoutOrThrow();m&&(yield this.paymentIntegrationService.applyStoreCredit(m));try{p&&(yield this.paymentIntegrationService.submitOrder(o,t)),c&&(yield this.paymentIntegrationService.loadPaymentMethod(c,{params:{method:l}}));const e=this.paymentIntegrationService.getState();if(Nd(d)){yield this.paymentIntegrationService.submitOrder(o,t);const{instrumentId:n}=d,i=e.getPaymentMethodOrThrow(r.methodId).clientToken;if(!i)throw new ni(ei.MissingPaymentMethod);return yield this.executeWithVaulted(r,n,h,i)}const m=e.getPaymentMethodOrThrow(l),y=yield this.confirmStripePayment(m),{clientToken:g,method:f}=m,{id:v}=null!==(i=null!==(n=y.paymentIntent)&&void 0!==n?n:y.paymentMethod)&&void 0!==i?i:{id:""};s=y.error,a={credit_card_token:{token:v},vault_payment_instrument:u,confirm:!1,set_as_default_stored_instrument:h},f===Kp.CreditCard&&(a.client_token=g),p||(yield this.paymentIntegrationService.submitOrder(o,t));const _=this.buildPaymentPayload(l,a,h);yield this.paymentIntegrationService.submitPayment(_)}catch(e){yield this.processAdditionalAction(this.handleEmptyPaymentIntentError(e,s),l,u,h)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this.hostedForm&&this.hostedForm.detach(),this.isDeinitialize=!0,this.unmountElement(),Promise.resolve()}buildPaymentPayload(e,t,n){return{methodId:e,paymentData:n?{formattedPayload:Object.assign(Object.assign({},t),{set_as_default_stored_instrument:n})}:{formattedPayload:t}}}isCancellationError(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))}isAuthError(e){return"payment_intent_authentication_failure"===(null==e?void 0:e.code)}isCreditCard(e){return e===Jp.CreditCard}isHostedFieldAvailable(){var e;const t=this.getInitializeOptions(),n=ue(null===(e=t.form)||void 0===e?void 0:e.fields,$);return!$(n)}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:n}=this.paymentIntegrationService.getState(),i=n(e,t);return Boolean(i.config.isHostedFormEnabled)}confirmStripePayment(e){return Xp(this,void 0,void 0,function*(){const{clientToken:t,method:n,returnUrl:i}=e;if(!t)throw new ni(ei.MissingPaymentMethod);switch(n){case Kp.Alipay:return this.getStripeJs().confirmAlipayPayment(t,{return_url:i},{handleActions:!1});case Kp.IDEAL:{const e=this.mapStripePaymentData(Jp.IDEAL,i);return this.getStripeJs().confirmIdealPayment(t,e,{handleActions:!1})}case Kp.Sepa:{const e=this.mapStripePaymentData(Jp.Sepa);return this.getStripeJs().confirmSepaDebitPayment(t,e)}default:{const e=this.useIndividualCardFields?this.getStripeCardElements()[0]:this.getStripeElement(),t=this.mapStripeBillingDetails(this.paymentIntegrationService.getState().getBillingAddress(),this.paymentIntegrationService.getState().getCustomer()),n=this._allowRedisplayForStoredInstruments;return this.getStripeJs().createPaymentMethod(Object.assign({type:Jp.CreditCard,card:e,billing_details:t},n?{allow_redisplay:"always"}:{}))}}})}executeWithVaulted(e,t,n,i){var r;return Xp(this,void 0,void 0,function*(){const o={bigpay_token:{token:t},confirm:!0,client_token:i,set_as_default_stored_instrument:n};if(this.isHostedPaymentFormEnabled(e.methodId,e.gatewayId)&&this.hostedForm){const t=this.hostedForm;return e.paymentData&&Nd(e.paymentData)&&(e.paymentData=Object.assign(Object.assign({},e.paymentData),{instrumentId:JSON.stringify({token:(null===(r=e.paymentData)||void 0===r?void 0:r.instrumentId)||"",client_token:i})})),yield t.validate(),yield t.submit(e),this.paymentIntegrationService.loadCurrentOrder()}const a=this.buildPaymentPayload(e.methodId,o,n);return this.paymentIntegrationService.submitPayment(a)})}getInitializeOptions(){if(!this.initializeOptions)throw new ri(ti.PaymentNotInitialized);return this.initializeOptions}getStripeCardElements(){if(!this.stripeCardElements)throw new ri(ti.PaymentNotInitialized);return this.stripeCardElements}getStripeElement(){if(!this.stripeElement)throw new ri(ti.PaymentNotInitialized);return this.stripeElement}getStripeJs(){if(!this.stripeV3Client)throw new ri(ti.PaymentNotInitialized);return this.stripeV3Client}handleEmptyPaymentIntentError(e,t){return pa(e)&&fe(e.body.errors,{code:"required_field"})&&t?new Error(t.message):e}loadStripeJs(e,t){return Xp(this,void 0,void 0,function*(){return this.stripeV3Client?Promise.resolve(this.stripeV3Client):this.scriptLoader.load(e,t,this.paymentIntegrationService.getState().getLocale())})}mapStripeAddress(e){if(e){const{city:t,countryCode:n,address1:i,address2:r,postalCode:o,stateOrProvinceCode:a}=e;return{city:t,country:n,line1:i,line2:r,postal_code:o,state:a}}return{line1:""}}mapStripeBillingDetails(e,t){const{firstName:n,lastName:i}=e||t||{firstName:"Guest",lastName:""},r=`${n} ${i}`.trim(),{options:o}=this.getInitializeOptions();if(this.useIndividualCardFields&&$p(o)){const{zipCodeElementOptions:t}=o;if(t){const n=document.getElementById(t.containerId)?document.getElementById(t.containerId).value:"";n&&e&&(e=Object.assign(Object.assign({},e),{postalCode:n}))}}const a={address:this.mapStripeAddress(e)};if(t&&t.addresses[0]&&function(e){return"object"==typeof e&&null!==e&&"id"in e&&void 0!==e.id}(t.addresses[0])){const e=t.addresses[0],{email:n}=t,{phone:i}=e;return i?Object.assign(Object.assign({},a),{email:n,name:r,phone:i}):Object.assign(Object.assign({},a),{email:n,name:r})}if(e){const{email:t,phone:n}=e;return n?Object.assign(Object.assign({},a),{email:t,name:r,phone:n}):Object.assign(Object.assign({},a),{email:t,name:r})}return Object.assign(Object.assign({},a),{name:r})}mapStripePaymentData(e,t){const n=this.paymentIntegrationService.getState().getCustomer(),i=this.paymentIntegrationService.getState().getBillingAddress(),r={payment_method:{[e]:this.getStripeElement(),billing_details:this.mapStripeBillingDetails(i,n)}};return e===Jp.IDEAL?Object.assign(Object.assign({},r),{return_url:t}):r}mountCardFields(e){const{options:t,containerId:n}=this.getInitializeOptions();let i;return new Promise((r,o)=>{switch(this.stripeElements||(this.stripeElements=this.getStripeJs().elements()),e){case Kp.CreditCard:if(this.useIndividualCardFields&&$p(t)){const{cardNumberElementOptions:e,cardExpiryElementOptions:n,cardCvcElementOptions:r}=t,a=this.stripeElements.getElement(Kp.CardNumber)||this.stripeElements.create(Kp.CardNumber,e),s=this.stripeElements.getElement(Kp.CardExpiry)||this.stripeElements.create(Kp.CardExpiry,n),d=this.stripeElements.getElement(Kp.CardCvc)||this.stripeElements.create(Kp.CardCvc,r);this.stripeCardElements=[a,s,d],i=this.stripeCardElements[0];try{a.mount(`#${e.containerId}`),s.mount(`#${n.containerId}`),d.mount(`#${r.containerId}`)}catch(e){this.isDeinitialize||o(new vi("Unable to mount Stripe component without valid container ID."))}}else{i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new vi("Unable to mount Stripe component without valid container ID."))}}break;case Kp.IDEAL:case Kp.Sepa:i=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{i.mount(`#${n}`)}catch(e){this.isDeinitialize||o(new vi("Unable to mount Stripe component without valid container ID."))}case Kp.Alipay:}r(i)})}mountCardVerificationFields(e){return Xp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getStoreConfig();if(!t)throw new ni(ei.MissingCheckoutConfig);const n=t.paymentSettings.bigpayBaseUrl,i=this.paymentIntegrationService.createHostedForm(n,e);return yield i.attach(),i})}processAdditionalAction(e,t,n=!1,i=!1){return Xp(this,void 0,void 0,function*(){if(!pa(e))throw e;const r=fe(e.body.errors,{code:"additional_action_required"}),o=fe(e.body.errors,{code:"three_d_secure_required"});if(r){const t=e.body.additional_action_required;if(t&&"redirect_to_url"===t.type)return new Promise(()=>{t.data.redirect_url&&window.location.replace(t.data.redirect_url)})}if(o){const r=e.body.three_ds_result.token,o=!1;let a,s=!1;try{a=yield this.getStripeJs().confirmCardPayment(r)}catch(e){s=!0}if(null==a?void 0:a.error){if(this.isCancellationError(a.error))throw new Wi;if(this.isAuthError(a.error))throw new Qp(Zp.AuthFailure);throw new Error(a.error.message)}const d={credit_card_token:{token:this.getPaymentToken(null==a?void 0:a.paymentIntent,r,s)},vault_payment_instrument:n,confirm:o},c=this.buildPaymentPayload(t,d,i);try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){throw this.handleEmptyPaymentIntentError(e,null==a?void 0:a.error)}}throw e})}getPaymentToken(e,t,n){return!e||n?t:e.id}shouldShowTSVHostedForm(e,t){return this.isHostedFieldAvailable()&&this.isHostedPaymentFormEnabled(e,t)}unmountElement(){this.stripeElement&&(this.stripeElement.unmount(),this.stripeElement=void 0)}}class nm{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}load(e,t,n){return this.scriptLoader.loadScript("https://js.stripe.com/v3/").then(()=>{if(!this.stripeWindow.Stripe)throw new mi;return this.stripeWindow.Stripe(e,{stripeAccount:t,locale:n,betas:["payment_intent_beta_3","alipay_pm_beta_1"],apiVersion:"2020-03-02;alipay_beta=v1"})})}}const im=fi(e=>new tm(e,new nm(a())),[{gateway:"stripev3"}]),rm={ar:["ar"],bg:["bg"],cs:["cs"],da:["da"],de:["de"],el:["el"],en:["en","en-GB"],es:["es","es-419"],et:["et"],fi:["fi"],fil:["fil"],fr:["fr","fr-CA"],he:["he"],hr:["hr"],hu:["hu"],id:["id"],it:["it"],ja:["ja"],ko:["ko"],lt:["lt"],lv:["lv"],ms:["ms"],mt:["mt"],nb:["nb"],nl:["nl"],pl:["pl"],pt:["pt","pt-BR"],ro:["ro"],ru:["ru"],sk:["sk"],sl:["sl"],sv:["sv"],th:["th"],tr:["tr"],vi:["vi"],zh:["zh","zh-HK","zh-TW"]};function om(e){const[t,n]=e.replace(/_/g,"-").toLowerCase().split("-"),i=rm[t];if(!i)return"auto";const r=n?`${t}-${n.toUpperCase()}`:t;return i.indexOf(r)>-1?r:i[0]}var am=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class sm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){return am(this,void 0,void 0,function*(){const{stripeupe:t,methodId:n,gatewayId:i}=e;if(!(null==t?void 0:t.containerId))throw new ri(ti.PaymentNotInitialized);if(!i)throw new vi('Unable to initialize payment because "gatewayId" argument is not provided.');return this._loadStripeElement(t,i,n).catch(e=>{var n;return null===(n=t.onError)||void 0===n?void 0:n.call(t,e)}),this.stripeIntegrationService.initCheckoutEventsSubscription(i,n,t,this._stripeElements),Promise.resolve()})}execute(e,t){return am(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n||!n.paymentData)throw new co(["payment.paymentData"]);if(!this._stripeUPEClient)throw new ri(ti.PaymentNotInitialized);const{paymentData:r,methodId:o,gatewayId:a}=n,{shouldSaveInstrument:s=!1,shouldSetAsDefaultInstrument:d=!1}=Bd(r)?r:{},c=this.paymentIntegrationService.getState(),{isStoreCreditApplied:l}=c.getCheckoutOrThrow(),u=c.getPaymentProviderCustomerOrThrow(),h=(cd(u)?u:{}).stripeLinkAuthenticationState;if(l&&(yield this.paymentIntegrationService.applyStoreCredit(l)),a){yield this.stripeIntegrationService.updateStripePaymentIntent(a,o);const{email:e}=c.getCustomerOrThrow();if(void 0!==h&&!e){const e=c.getBillingAddressOrThrow();yield this.paymentIntegrationService.updateBillingAddress(e)}}if(yield this.paymentIntegrationService.submitOrder(i,t),Nd(r)){const{instrumentId:e}=r;return void(yield this._executeWithVaulted(n.methodId,e,d))}yield this._executeWithStripeConfirmation(n.methodId,n.gatewayId,!h&&s,d)})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Da.PAYMENT))||void 0===t||t.unmount(),this.stripeIntegrationService.deinitialize(),this._stripeElements=void 0,this._stripeUPEClient=void 0,Promise.resolve()}_executeWithStripeConfirmation(e,t,n,i){return am(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),{clientToken:o}=r.getPaymentMethodOrThrow(e),a=this._getPaymentPayload(e,o||"",n,i);try{yield this.paymentIntegrationService.submitPayment(a)}catch(r){yield this._processAdditionalActionWithStripeConfirmation(r,e,t,n,i)}})}_executeWithVaulted(e,t,n){var i;return am(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(e),a=null===(i=r.getCart())||void 0===i?void 0:i.id;try{const i={methodId:e,paymentData:{formattedPayload:{cart_id:a,bigpay_token:{token:t},confirm:!1,client_token:o.clientToken,set_as_default_stored_instrument:n}}};return yield this.paymentIntegrationService.submitPayment(i)}catch(t){return this._processVaultedAdditionalAction(t,e,n)}})}_loadStripeElement(e,t,n){return am(this,void 0,void 0,function*(){const{containerId:i,style:r,render:o,initStripeElementUpdateTrigger:a}=e,s=yield this.paymentIntegrationService.loadPaymentMethod(t,{params:{method:n}}),d=s.getPaymentMethodOrThrow(n);if(!dd(d))throw new ni(ei.MissingPaymentMethod);const{clientToken:c,initializationData:l}=d,{shopperLanguage:u,allowRedisplayForStoredInstruments:h=!1,enableLink:p}=l;if(this._allowRedisplayForStoredInstruments=h,!c)throw new ni(ei.MissingPaymentMethod);let m;if(this._stripeUPEClient=yield this._loadStripeJs(l),this._isStripeElementUpdateEnabled="function"==typeof a,r){const e=r;m={variables:this.stripeIntegrationService.mapAppearanceVariables(r),rules:{".Input":this.stripeIntegrationService.mapInputAppearanceRules(e)}}}this._stripeElements=yield this.scriptLoader.getElements(this._stripeUPEClient,{clientSecret:c,locale:om(u),appearance:m});const{getBillingAddress:y,getShippingAddress:g}=s,{postalCode:f}=g()||y()||{},v=this._stripeElements.getElement(Da.PAYMENT)||this._stripeElements.create(Da.PAYMENT,Object.assign({fields:{billingDetails:{email:Ta.NEVER,address:{country:Ta.NEVER,city:Ta.NEVER,postalCode:f?Ta.NEVER:Ta.AUTO}}},wallets:{applePay:Ta.NEVER,googlePay:Ta.NEVER,link:p?Ta.AUTO:Ta.NEVER}},this._getStripeElementTerms()));this.stripeIntegrationService.mountElement(v,i),v.on(za.READY,()=>{o()}),v.on(za.CHANGE,e=>{(null==e?void 0:e.value)&&"type"in e.value&&this._updateStripeLinkStateByElementType(e.value.type)}),this._isStripeElementUpdateEnabled&&(null==a||a(this._updateStripeElement.bind(this)))})}_processAdditionalActionWithStripeConfirmation(e,t,n,i=!1,r=!1){return am(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ti.PaymentNotInitialized);const{data:o}=e.body.additional_action_required,{token:a}=o,{paymentIntent:s,error:d}=yield this._confirmStripePaymentOrThrow(t,o),c=this._getPaymentPayload(t,(null==s?void 0:s.id)||a,i,r);if(d||!s){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(d)}try{yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return am(this,void 0,void 0,function*(){if(!this._stripeUPEClient)throw new ri(ti.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,i,!!this._allowRedisplayForStoredInstruments);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this._stripeUPEClient))?this._stripeUPEClient.retrievePaymentIntent(n||""):this._stripeUPEClient.confirmPayment(r)})}_processVaultedAdditionalAction(e,t,n=!1){var i;return am(this,void 0,void 0,function*(){if(!t||!pa(e)||!fe(e.body.errors,{code:"three_d_secure_required"}))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new ri(ti.PaymentNotInitialized);const r=e.body.three_ds_result.token;let o,a=!1;try{o=yield this._stripeUPEClient.confirmCardPayment(r)}catch(e){try{o=yield this._stripeUPEClient.retrievePaymentIntent(r)}catch(e){a=!0}}if((null==o?void 0:o.error)&&this.stripeIntegrationService.throwStripeError(o.error),!(null==o?void 0:o.paymentIntent)&&!a)throw new nr;const s=this._getPaymentPayload(t,a?r:null===(i=null==o?void 0:o.paymentIntent)||void 0===i?void 0:i.id,!1,n);return this.paymentIntegrationService.submitPayment(s)})}_loadStripeJs(e){return am(this,void 0,void 0,function*(){if(this._stripeUPEClient)return this._stripeUPEClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.V3,Fa,La)})}_getPaymentPayload(e,t,n=!1,i=!1){var r;return{methodId:e,paymentData:{formattedPayload:{cart_id:(null===(r=this.paymentIntegrationService.getState().getCart())||void 0===r?void 0:r.id)||"",credit_card_token:{token:t},confirm:!1,vault_payment_instrument:n,set_as_default_stored_instrument:i}}}}_updateStripeElement({shouldShowTerms:e}){var t;const n=null===(t=this._stripeElements)||void 0===t?void 0:t.getElement(Da.PAYMENT);null==n||n.update(Object.assign({},this._getStripeElementTerms(e)))}_getStripeElementTerms(e){let t=Ta.AUTO;return this._isStripeElementUpdateEnabled&&(t=e?Ta.AUTO:Ta.NEVER),{terms:{card:t}}}_updateStripeLinkStateByElementType(e){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),n=e===Aa.Link;!cd(t)&&n&&this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:n})}}const dm=fi(e=>{const t=new Ra(a());return new sm(e,t,new pd(e,t))},[{gateway:"stripeupe"},{gateway:"stripeupe",id:"klarna"}]),cm=e=>"object"==typeof e&&null!==e&&"value"in e&&"collapsed"in e;var lm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class um{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return lm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId))throw new ri(ti.PaymentNotInitialized);if(!r)throw new vi('Unable to initialize payment because "gatewayId" argument is not provided.');try{yield this._initializeStripeElement(n,r,i)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}this.stripeIntegrationService.initCheckoutEventsSubscription(r,i,n,this.stripeElements)})}execute(e,t){return lm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{methodId:r,gatewayId:o}=n||{};if(!this.stripeClient)throw new ri(ti.PaymentNotInitialized);if(!o||!r)throw new vi('Unable to initialize payment because "gatewayId" or "methodId" argument is not provided.');const{isStoreCreditApplied:a}=this.paymentIntegrationService.getState().getCheckoutOrThrow();a&&(yield this.paymentIntegrationService.applyStoreCredit(a)),yield this.stripeIntegrationService.updateStripePaymentIntent(o,r),yield this.paymentIntegrationService.submitOrder(i,t);const{clientToken:s}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(r,o),d=this._getPaymentPayload(r,s||"");try{yield this.paymentIntegrationService.submitPayment(d)}catch(e){yield this._processAdditionalAction(e,r,o)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Da.PAYMENT);return null==t||t.unmount(),null==t||t.destroy(),this.stripeIntegrationService.deinitialize(),this.stripeElements=void 0,this.stripeClient=void 0,Promise.resolve()}_initializeStripeElement(e,t,n){return lm(this,void 0,void 0,function*(){let i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t);if((null==i?void 0:i.clientToken)||(i=(yield this.paymentIntegrationService.loadPaymentMethod(t,{params:{method:n}})).getPaymentMethodOrThrow(n,t)),!dd(i))throw new ni(ei.MissingPaymentMethod);const{clientToken:r,initializationData:o}=i,{customerSessionToken:a,enableLink:s}=o;if(!r)throw new ni(ei.MissingPaymentMethod);this.stripeClient=yield this._loadStripeJs(o);const{appearance:d,containerId:c,fonts:l,layout:u,render:h,paymentMethodSelect:p,handleClosePaymentMethod:m,togglePreloader:y}=e;this.stripeElements=yield this.scriptLoader.getElements(this.stripeClient,{clientSecret:r,customerSessionClientSecret:a,appearance:d,fonts:l});const{getBillingAddress:g,getShippingAddress:f}=this.paymentIntegrationService.getState(),v=g(),{postalCode:_}=f()||v||{},S=this.stripeElements.getElement(Da.PAYMENT)||this.stripeElements.create(Da.PAYMENT,{fields:{billingDetails:{email:Ta.NEVER,address:{country:Ta.NEVER,city:Ta.NEVER,postalCode:_?Ta.NEVER:Ta.AUTO}}},wallets:{applePay:Ta.NEVER,googlePay:Ta.NEVER,link:s?Ta.AUTO:Ta.NEVER},layout:u,savePaymentMethod:{maxVisiblePaymentMethods:20},defaultValues:{billingDetails:{email:(null==v?void 0:v.email)||""}}});this.stripeIntegrationService.mountElement(S,c),S.on(za.LOADER_START,()=>{null==y||y(!1)}),S.on(za.READY,()=>{h()}),S.on(za.CHANGE,e=>{this._onStripeElementChange(e,t,n,p)}),null==m||m(this._collapseStripeElement.bind(this))})}_loadStripeJs(e){return lm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState(),n=this.stripeIntegrationService.getStripeJsVersion(e);return this.scriptLoader.getStripeClient(e,t.getCartLocale(),n)})}_collapseStripeElement(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Da.PAYMENT);null==t||t.collapse()}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",{card:o,us_bank_account:a}=n||{},s=this._shouldSaveInstrument(o)||this._shouldSaveInstrument(a),d=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:s},d)}}}_processAdditionalAction(e,t,n){return lm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this.stripeClient||!this.stripeElements)throw new ri(ti.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:r}=i,{paymentIntent:o,error:a}=yield this._confirmStripePaymentOrThrow(t,i),{client_secret:s,payment_method_options:d}=o||{},c=this._getPaymentPayload(t,s||r,d);if(a||!o){const{initializationData:e}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,n),{sendSecondPaymentRequestOnStripeError:i}=e||{};if(i)try{const e=de({},c,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}this.stripeIntegrationService.throwStripeError(a)}try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){return lm(this,void 0,void 0,function*(){if(!this.stripeClient)throw new ri(ti.PaymentNotInitialized);const{token:n,redirect_url:i}=t,r=this.stripeIntegrationService.mapStripePaymentData(this.stripeElements,i);return(yield this.stripeIntegrationService.isPaymentCompleted(e,this.stripeClient))?this.stripeClient.retrievePaymentIntent(n||""):this.stripeClient.confirmPayment(r)})}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_shouldSaveInstrument(e){const t=null==e?void 0:e.setup_future_usage;return t===xa.ON_SESSION||t===xa.OFF_SESSION}_getTokenizedOptions(e,t){return this._shouldSaveInstrument(null==t?void 0:t.us_bank_account)?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}}const hm=fi(e=>{const t=new Ra(a());return new um(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"optimized_checkout"}]);var pm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class mm{constructor(e,t,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=n}initialize(e){var t;return pm(this,void 0,void 0,function*(){const{stripeocs:n,methodId:i,gatewayId:r}=e;if(!(null==n?void 0:n.containerId)||!r)throw new ri(ti.PaymentNotInitialized);let o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r);(null==o?void 0:o.clientToken)||(yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:i}}),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,r));try{yield this._initStripeCheckoutSession(n,o),yield this._updateStripeShopperData(),this._initializePaymentElement(n,o),this._initializeAdaptivePricingElement(n,o)}catch(e){e instanceof Error&&(null===(t=n.onError)||void 0===t||t.call(n,e))}})}execute(e,t){return pm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{methodId:r,gatewayId:o}=n||{};if(!this.stripeClient)throw new ri(ti.PaymentNotInitialized);if(!o||!r)throw new vi('Unable to initialize payment because "gatewayId" or "methodId" argument is not provided.');const a=this.paymentIntegrationService.getState(),{isStoreCreditApplied:s}=a.getCheckoutOrThrow();s&&(yield this.paymentIntegrationService.applyStoreCredit(s)),yield this._updateCheckoutSessionData(o,r),yield this.paymentIntegrationService.submitOrder(i,t);const{clientToken:d}=a.getPaymentMethodOrThrow(r,o),c=this._getPaymentPayload(r,d||"");try{yield this.paymentIntegrationService.submitPayment(c)}catch(e){yield this._processAdditionalAction(e,o,r)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){var e,t;const n=null===(e=this.stripeCheckout)||void 0===e?void 0:e.getPaymentElement(),i=null===(t=this.stripeCheckout)||void 0===t?void 0:t.getCurrencySelectorElement();return null==n||n.unmount(),null==n||n.destroy(),null==i||i.unmount(),null==i||i.destroy(),this.stripeCheckout=void 0,this.stripeClient=void 0,this.selectedMethodId=void 0,Promise.resolve()}_initStripeCheckoutSession(e,t){return pm(this,void 0,void 0,function*(){const{clientToken:n,initializationData:i}=t;if(!n||!i)throw new ni(ei.MissingPaymentMethod);this.stripeClient=yield this._loadStripeJs(i);const{appearance:r,fonts:o}=e;this.stripeCheckout=yield this.scriptLoader.getStripeCheckout(this.stripeClient,{clientSecret:n,elementsOptions:{appearance:r,fonts:o},adaptivePricing:{allowed:!!(null==i?void 0:i.adaptivePricingEnabled)}})})}_initializePaymentElement(e,t){const{initializationData:n,id:i,gateway:r}=t,{enableLink:o}=n||{},{containerId:a,layout:s,render:d,paymentMethodSelect:c,handleClosePaymentMethod:l,togglePreloader:u}=e,h=this._getStripeElement({fields:{billingDetails:{email:Ta.NEVER,name:Ta.NEVER,address:Ta.NEVER}},wallets:{applePay:Ta.NEVER,googlePay:Ta.NEVER,link:o?Ta.AUTO:Ta.NEVER},layout:s});if(!h||!r)throw new ri(ti.PaymentNotInitialized);this.stripeIntegrationService.mountElement(h,a),h.on(za.LOADER_START,()=>{null==u||u(!1)}),h.on(za.READY,()=>{d()}),h.on(za.CHANGE,e=>{this._onStripeElementChange(e,r,i,c)}),null==l||l(this._collapseStripeElement.bind(this))}_loadStripeJs(e){return pm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ka.CLOVER)})}_getStripeActionsOrThrow(){return pm(this,void 0,void 0,function*(){if(!this.stripeCheckout)throw new ri(ti.PaymentNotInitialized);const{actions:e,error:t}=yield this.stripeCheckout.loadActions();if(!e||t)throw new Qr(null==t?void 0:t.message);return e})}_getStripeElement(e){var t,n;return(null===(t=this.stripeCheckout)||void 0===t?void 0:t.getPaymentElement())||(null===(n=this.stripeCheckout)||void 0===n?void 0:n.createPaymentElement(e))}_onStripeElementChange(e,t,n,i){cm(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==i||i(`${t}-${n}`))}_collapseStripeElement(){var e;const t=null===(e=this.stripeCheckout)||void 0===e?void 0:e.getPaymentElement();null==t||t.collapse()}_updateCheckoutSessionData(e,t){return pm(this,void 0,void 0,function*(){yield this._updateStripeShopperData(),yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}})})}_getPaymentPayload(e,t,n){var i;const r=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"",o=this._getTokenizedOptions(t,n);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:!!n},o)}}}_processAdditionalAction(e,t,n){var i;return pm(this,void 0,void 0,function*(){if(!pa(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;const{data:r}=(null===(i=e.body)||void 0===i?void 0:i.additional_action_required)||{},{token:o}=r||{},a=yield this._getStripeSavedPaymentMethodsOrThrow(),{session:s,error:d}=yield this._confirmStripePayment(r),c=yield this._getStripeSavedPaymentMethodsOrThrow(s),{id:l,status:u}=s||{},h=this._getNewVaultedStripeInstrument(a,c),p=this._getPaymentPayload(n,l||o,h),{initializationData:m}=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n,t),{sendSecondPaymentRequestOnStripeError:y}=m||{};if(d||!s){if(y)try{const e=de({},p,{paymentData:{formattedPayload:{client_side_error:!0}}});yield this.paymentIntegrationService.submitPayment(e)}catch(e){}throw new Qr(null==d?void 0:d.message)}try{return yield this.paymentIntegrationService.submitPayment(p)}catch(e){throw(null==u?void 0:u.paymentStatus)===Oa.Paid&&this.stripeIntegrationService.throwPaymentConfirmationProceedMessage(),e}})}_confirmStripePayment(e){return pm(this,void 0,void 0,function*(){const{redirect_url:t}=e||{};if(!this.stripeCheckout)throw new ri(ti.PaymentNotInitialized);return(yield this._getStripeActionsOrThrow()).confirm({redirect:Ta.IF_REQUIRED,returnUrl:t})})}_updateStripeShopperData(){return pm(this,void 0,void 0,function*(){const e=yield this._getStripeActionsOrThrow();yield this._updateStripeEmail(e),yield this._updateStripeShippingAddress(e),yield this._updateStripeBillingAddress(e)})}_updateStripeEmail(e){return pm(this,void 0,void 0,function*(){if((yield e.getSession()).email)return;const{getBillingAddress:t}=this.paymentIntegrationService.getState(),n=t();yield e.updateEmail((null==n?void 0:n.email)||"")})}_updateStripeShippingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getShippingAddress();t&&(yield e.updateShippingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_updateStripeBillingAddress(e){return pm(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getBillingAddress();t&&(yield e.updateBillingAddress({name:this.stripeIntegrationService.getShopperFullName(t),address:this.stripeIntegrationService.mapStripeAddress(t)}))})}_getStripeSavedPaymentMethodsOrThrow(e){return pm(this,void 0,void 0,function*(){if(null==e?void 0:e.savedPaymentMethods)return e.savedPaymentMethods;const t=yield this._getStripeActionsOrThrow(),{savedPaymentMethods:n}=yield t.getSession();return n||[]})}_getNewVaultedStripeInstrument(e,t){return t.find(t=>!e.some(e=>e.id===t.id))}_getTokenizedOptions(e,t){return(null==t?void 0:t.type)===Aa.ACH?{tokenized_ach:{token:e}}:{credit_card_token:{token:e}}}_initializeAdaptivePricingElement(e,t){const{initializationData:n}=t,{currencySelectorContainerId:i}=e;if(!(null==n?void 0:n.adaptivePricingEnabled))return;if(!i)throw new ri(ti.PaymentNotInitialized);const r=this._getCurrencySelectorElement();r&&(r.mount(`#${i}`),this._initAdaptivePricingEvents(r))}_getCurrencySelectorElement(){var e,t;return(null===(e=this.stripeCheckout)||void 0===e?void 0:e.getCurrencySelectorElement())||(null===(t=this.stripeCheckout)||void 0===t?void 0:t.createCurrencySelectorElement())}_initAdaptivePricingEvents(e){e.on(za.CHANGE,e=>pm(this,void 0,void 0,function*(){if(!e.value||!("currency"in e.value))return;const{currency:t}=this.paymentIntegrationService.getState().getCartOrThrow(),n=t.code.toLowerCase(),i=e.value.currency.toLowerCase();yield this.paymentIntegrationService.updatePaymentProviderCustomer({isCustomerCurrencySelected:n!==i,customerCurrency:i})}))}}const ym=fi(e=>{const t=new Ra(a());return new mm(e,t,new pd(e,t))},[{gateway:"stripeocs",id:"checkout_session"}]);var gm;!function(e){e.CARD_NUMBER="card-number",e.CVV="cvv",e.EXPIRY="expiry"}(gm||(gm={}));var fm=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class vm{constructor(e,t,n){this.paymentIntegrationService=e,this.tdOnlineMartScriptLoader=t,this.formPoster=n,this.tdInputs=[{id:"ccNumber",fieldType:gm.CARD_NUMBER},{id:"ccCvv",fieldType:gm.CVV},{id:"ccExpiry",fieldType:gm.EXPIRY}]}initialize(e){return fm(this,void 0,void 0,function*(){const{methodId:t}=e;if(!t)throw new vi('Unable to initialize payment because "options.methodId" argument is not provided.');this.tdOnlineMartClient=yield this.loadTDOnlineMartJs(),this.mountHostedFields(t)})}execute(e,t){return fm(this,void 0,void 0,function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);if(!n.methodId)throw new ni(ei.MissingPaymentMethod);const r=yield this.getPaymentPayloadOrThrow(n);yield this.paymentIntegrationService.submitOrder(i,t);try{yield this.paymentIntegrationService.submitPayment(r)}catch(e){yield this.processWithAdditionalAction(e)}})}finalize(){return Promise.reject(new Cd)}deinitialize(){return this.tdOnlineMartClient=void 0,this.tdInputs.forEach(({inputElement:e})=>{null==e||e.unmount()}),Promise.resolve()}getPaymentPayloadOrThrow(e){return fm(this,void 0,void 0,function*(){const{methodId:t,paymentData:n}=e,{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:r=!1}=Bd(n)?n:{},o={browser_info:ss(),shouldSaveInstrument:i,shouldSetAsDefaultInstrument:r};if(Bd(n)&&Nd(n)&&n.instrumentId){const e=!!this.paymentIntegrationService.getState().getCartOrThrow().lineItems.digitalItems.length,i=!this.isTrustedVaultingInstrument(n.instrumentId)||e;return{methodId:t,paymentData:Object.assign(Object.assign(Object.assign({},o),{instrumentId:n.instrumentId}),i?{nonce:n.instrumentId}:{})}}let a;try{a=yield this.getTokenOrThrow()}catch(e){this.throwTokenizationError(e)}return{methodId:t,paymentData:Object.assign(Object.assign({},o),{nonce:a})}})}mountHostedFields(e){const t=this.getHostedFieldsOptions(),n=this.getTDOnlineMartClientOrThrow();this.tdInputs.forEach(i=>{const r=`${e}-${i.id}`;document.getElementById(r)&&(i.inputElement=n.create(i.fieldType,t),i.inputElement.mount(`#${r}`))})}loadTDOnlineMartJs(){return fm(this,void 0,void 0,function*(){return this.tdOnlineMartClient?this.tdOnlineMartClient:this.tdOnlineMartScriptLoader.load()})}getTokenOrThrow(){return new Promise((e,t)=>{this.getTDOnlineMartClientOrThrow().createToken(n=>{const{error:i,token:r}=n;if(i||!r)return t(i);e(r)})})}getTDOnlineMartClientOrThrow(){if(!this.tdOnlineMartClient)throw new ri(ti.PaymentNotInitialized);return this.tdOnlineMartClient}processWithAdditionalAction(e){return fm(this,void 0,void 0,function*(){if(!function(e){return pa(e)&&(t=e.body,Z(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&W(t.errors)&&fe(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:n,payer_auth_request:i,merchant_data:r}=t||{};if(!n||!i||!r)throw new co(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(n,{threeDSSessionData:i,creq:r},e,"_top")})})}throwTokenizationError(e){if(!function(e){return"object"==typeof e&&null!==e&&"field"in e&&"type"in e&&"message"in e}(e))throw new ni(ei.MissingPaymentToken);throw new Error(e.message)}getHostedFieldsOptions(){return{style:{error:{color:"#d14343"}},classes:{error:"form-input--error"}}}isTrustedVaultingInstrument(e){const t=this.paymentIntegrationService.getState().getInstruments(),n=null==t?void 0:t.find(t=>uc(t)&&t.bigpayToken===e);return!(uc(n)&&!n.trustedShippingAddress)}}class _m{constructor(e,t=window){this.scriptLoader=e,this.tdOnlineMartWindow=t}load(){return e=this,t=void 0,i=function*(){if(this.tdOnlineMartWindow.customcheckout||(yield this.scriptLoader.loadScript("https://libs.na.bambora.com/customcheckout/1/customcheckout.js")),!this.tdOnlineMartWindow.customcheckout)throw new mi;return this.tdOnlineMartWindow.customcheckout()},new((n=void 0)||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())});var e,t,n,i}}const Sm=fi(e=>new vm(e,new _m(a()),Ee()),[{id:"tdonlinemart"}]);var Im=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};const wm="Payment cannot continue";let Cm;class bm extends tu{initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Im(this,void 0,void 0,function*(){if(this._initializeOptions=e&&e.worldpay,!this._initializeOptions)throw new ri(ti.PaymentNotInitialized);return t.initialize.call(this,e)})}execute(e,t){const n=Object.create(null,{execute:{get:()=>super.execute}});return Im(this,void 0,void 0,function*(){const{payment:i}=e;if(Cm=this._submitAdditionalAction(),!i)throw new co(["payment"]);try{return yield n.execute.call(this,e,t)}catch(e){return this._processAdditionalAction(e,i)}})}_processAdditionalAction(e,t){return Im(this,void 0,void 0,function*(){return pa(e)&&fe(e.body.errors,{code:"additional_action_required"})?new Promise((n,i)=>{const r=e=>Im(this,void 0,void 0,function*(){if(-1===e.origin.indexOf("cardinalcommerce.com"))return;if("string"!=typeof e.data||!this._isValidJsonWithSessionId(e.data))return i(new Error(wm));window.removeEventListener("message",r),o.remove();const a=JSON.parse(e.data),s=de({},t,{paymentData:{threeDSecure:{token:a.SessionId}}});try{n(yield Cm(s))}catch(e){if(!pa(e)||!fe(e.body.errors,{code:"three_d_secure_required"}))return i(e);if(!this._initializeOptions)return i(new ri(ti.PaymentNotInitialized));const{onLoad:t}=this._initializeOptions,n=this._createIframe(e.body.three_ds_result);try{t(n,()=>i(new Error("Payment was cancelled")))}catch(e){i(new Error(wm))}}});let o;window.addEventListener("message",r);try{o=this._createHiddenIframe(e.body)}catch(e){throw window.removeEventListener("message",r),new Error(wm)}}):Promise.reject(e)})}_createHiddenIframe(e){const t=document.createElement("iframe");if(document.body.appendChild(t),!t.contentWindow)throw new Error;t.id="worldpay_hosted_hidden_payment_page",t.height="0px",t.width="0px";const n=document.createElement("form"),i="collectionForm";n.id=i,n.name="devicedata",n.method="post";const r=e.additional_action_required.data.redirect_url;n.action=r;const o=document.createElement("input");o.name="Bin",o.type="hidden",o.value=e.provider_data.source_id,n.appendChild(o);const a=document.createElement("input");a.name="JWT",a.type="hidden",a.value=e.provider_data.data,n.appendChild(a);const s=document.createElement("button");s.type="submit",s.id="btnsubmit",n.appendChild(s),navigator.userAgent.match("Firefox")?t.srcdoc=n.outerHTML:t.contentWindow.document.body.appendChild(n);const d=document.createElement("script");return d.innerHTML=`\n document.getElementById('${i}').submit();\n `,t.contentWindow.document.body.appendChild(d),t}_createIframe(e){const t=document.createElement("form");t.id="challengeForm",t.method="POST",t.action=e.acs_url;const n=document.createElement("input");n.name="JWT",n.type="hidden",n.value=e.payer_auth_request,t.appendChild(n);const i=document.createElement("input");i.name="MD",i.type="hidden",i.value=`merchantSessionId=${e.merchant_data}`,t.appendChild(i);const r=document.createElement("script");r.type="text/javascript",r.innerHTML="window.onload = function() { document.getElementById('challengeForm').submit(); }";const o=document.createElement("iframe");return o.name="worldpay_hosted_payment_page",o.height="400",o.width="100%",o.srcdoc=`${t.outerHTML} ${r.outerHTML}`,o}_submitAdditionalAction(){if(this._shouldRenderHostedForm){if(!this._hostedForm)throw new ri(ti.PaymentNotInitialized);const e=this._hostedForm;return t=>Im(this,void 0,void 0,function*(){yield e.submit(t)})}return e=>Im(this,void 0,void 0,function*(){yield this._paymentIntegrationService.submitPayment(e)})}_isValidJsonWithSessionId(e){try{const t=JSON.parse(e);return!(!t.SessionId||!t.Status)}catch(e){return!1}}}const Pm=fi(e=>new bm(e),[{gateway:"worldpayaccess",id:"credit_card"},{id:"worldpayaccess"}]);class Om{constructor(e){this._paymentIntegrationService=e}execute({payment:e}){return t=this,n=void 0,r=function*(){if(!e)throw new co(["payment"]);yield this._paymentIntegrationService.submitOrder();try{yield this._paymentIntegrationService.submitPayment(e)}catch(e){if(this._isWorldpayAccessRedirectResponse(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise(()=>window.location.replace(t))}return Promise.reject(e)}},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_isWorldpayAccessRedirectResponse(e){var t,n;if("object"!=typeof e||null===e)return!1;const i=e;if(!i.body)return!1;const r=i.body;return"additional_action_required"===r.status&&!!(null===(n=null===(t=r.additional_action_required)||void 0===t?void 0:t.data)||void 0===n?void 0:n.redirect_url)}}const Em=fi(e=>new Om(e),[{id:"open_banking",gateway:"worldpayaccess"}]);class Am{constructor(e){this._requestSender=e}saveExternalId(e,t){return n=this,i=void 0,o=function*(){const n=`/api/storefront/payment/${e}/save-external-id`,i={headers:Object.assign({Accept:mr.JsonV1,"X-API-INTERNAL":hr},yr),body:{externalId:t,provider:e}};yield this._requestSender.post(n,i)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}}class Tm{constructor(e,t){this.paymentIntegrationService=e,this.storefrontPaymentRequestSender=t}initialize(){return Promise.resolve()}execute(e,t){return n=this,i=void 0,o=function*(){const{payment:n}=e,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);if(!n)throw new co(["payment"]);const{methodId:r}=n,{getPaymentMethodOrThrow:o}=yield this.paymentIntegrationService.loadPaymentMethod(r,t),{clientToken:a,initializationData:s}=o(r),d=null==s?void 0:s.redirectUrl;if(!a||!d)throw new ni(ei.MissingPaymentMethod);const{id:c}=JSON.parse(a);if(!c)throw new ni(ei.MissingPaymentToken);const{isStoreCreditApplied:l}=this.paymentIntegrationService.getState().getCheckoutOrThrow();yield this.paymentIntegrationService.applyStoreCredit(l),yield this.paymentIntegrationService.initializePayment(r,{useStoreCredit:l}),yield this.paymentIntegrationService.submitOrder(i,t),yield this._prepareForReferredRegistration(r,c);try{yield this.paymentIntegrationService.submitPayment({methodId:r,paymentData:{nonce:c}})}catch(e){if(pa(e)&&"additional_action_required"===e.body.status)return new Promise(()=>window.location.replace(d));throw e}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}finalize(){return Promise.reject(new Cd)}deinitialize(){return Promise.resolve()}_prepareForReferredRegistration(e,t){return this.storefrontPaymentRequestSender.saveExternalId(e,t)}}const km=fi(e=>{const{getHost:t}=e.getState(),i=n({host:t()}),r=new Am(i);return new Tm(e,r)},[{id:"zip"},{id:"quadpay"}]);var Dm,Mm;!function(e){e.LoadCountriesRequested="LOAD_COUNTRIES_REQUESTED",e.LoadCountriesSucceeded="LOAD_COUNTRIES_SUCCEEDED",e.LoadCountriesFailed="LOAD_COUNTRIES_FAILED"}(Dm||(Dm={}));class zm{constructor(e){this._countryRequestSender=e}loadCountries(e){return m.create(t=>{t.next(l(Dm.LoadCountriesRequested)),this._countryRequestSender.loadCountries(e).then(e=>{t.next(l(Dm.LoadCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Dm.LoadCountriesFailed,e))})})}}class xm{constructor(e,t){this._requestSender=e,this._config=t}loadCountries({timeout:e}={}){const t=Object.assign({"Accept-Language":this._config.locale},et);return this._requestSender.get("/internalapi/v1/store/countries",{headers:t,timeout:e})}}class Nm extends rt{constructor(e){super(e||"Your checkout could not be processed because some details have changed. Please review your order and try again."),this.name="CartConsistencyError",this.type="cart_consistency"}}class Rm extends rt{constructor(e,t){super(t||"At least one item changed stock position. Please review your cart and try again."),this.name="CartStockPositionsChangedError",this.type="cart_stock_positions_changed",this.changedItemIds=e}}class Fm extends rt{constructor(e){super(e||"The tax provider is unavailable."),this.name="OrderTaxProviderUnavailableError",this.type="tax_provider_unavailable"}}class Lm extends rt{constructor(e){super(e),this.name="MissingShippingMethodError",this.type="missing_shipping_method"}}class jm extends rt{constructor(e){super(e),this.name="InvalidShippingAddressError",this.type="invalid_shipping_address"}}class Bm{constructor(e){this._requestSender=e}loadOrder(e,{timeout:t}={}){const n=`/api/storefront/orders/${e}`,i=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.get(n,{params:{include:Lt(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:t})}submitOrder(e,{headers:t,timeout:n}={}){return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:ue(Object.assign({"X-Checkout-Variant":t&&t.checkoutVariant},et),J),timeout:n}).catch(e=>{var t,n;if("tax_provider_unavailable"===e.body.type)throw new Fm;if("cart_has_changed"===e.body.type)throw new Nm;if("cart_stock_positions_changed"===e.body.type){const i=null!==(n=null===(t=e.body.errors)||void 0===t?void 0:t.changedItemIds)&&void 0!==n?n:[];throw new Rm(i)}if("missing_shipping_method"===e.body.type)throw new Lm(e.body.detail);if("invalid_shipping_address"===e.body.type)throw new jm(e.body.detail);if("empty_cart"===e.body.type)throw new ct;throw e})}finalizeOrder(e,{timeout:t}={}){const n=`/internalapi/v1/checkout/order/${e}`;return this._requestSender.post(n,{timeout:t,headers:et})}}class Um extends rt{constructor(){super("You haven't complete our spam check. Please try again."),this.name="SpamProtectionNotCompletedError",this.type="spam_protection_not_completed"}}!function(e){e.LoadOrderRequested="LOAD_ORDER_REQUESTED",e.LoadOrderSucceeded="LOAD_ORDER_SUCCEEDED",e.LoadOrderFailed="LOAD_ORDER_FAILED",e.LoadOrderPaymentsRequested="LOAD_ORDER_PAYMENTS_REQUESTED",e.LoadOrderPaymentsSucceeded="LOAD_ORDER_PAYMENTS_SUCCEEDED",e.LoadOrderPaymentsFailed="LOAD_ORDER_PAYMENTS_FAILED",e.SubmitOrderRequested="SUBMIT_ORDER_REQUESTED",e.SubmitOrderSucceeded="SUBMIT_ORDER_SUCCEEDED",e.SubmitOrderFailed="SUBMIT_ORDER_FAILED",e.FinalizeOrderRequested="FINALIZE_ORDER_REQUESTED",e.FinalizeOrderSucceeded="FINALIZE_ORDER_SUCCEEDED",e.FinalizeOrderFailed="FINALIZE_ORDER_FAILED"}(Mm||(Mm={}));var qm;class Vm{constructor(e,t){this._orderRequestSender=e,this._checkoutValidator=t}loadOrder(e,t){return new m(n=>{n.next(l(Mm.LoadOrderRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderFailed,e))})})}loadOrderPayments(e,t){return new m(n=>{n.next(l(Mm.LoadOrderPaymentsRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{n.next(l(Mm.LoadOrderPaymentsSucceeded,e.body)),n.complete()}).catch(e=>{n.error(h(Mm.LoadOrderPaymentsFailed,e))})})}loadCurrentOrder(e){return t=>f(()=>{const n=this._getCurrentOrderId(t.getState());if(!n)throw new ot(tt.MissingOrderId);return this.loadOrder(n,e)})}submitOrder(e,t){return n=>g(C(l(Mm.SubmitOrderRequested)),f(()=>{const i=n.getState(),r=i.config.getExternalSource(),o=i.config.getVariantIdentificationToken(),a=i.checkout.getCheckout();if(!a)throw new ot(tt.MissingCheckout);if(a.shouldExecuteSpamCheck)throw new Um;return _(this._checkoutValidator.validate(a,t).then(()=>this._orderRequestSender.submitOrder(this._mapToOrderRequestBody(null!=e?e:{},a.id,a.customerMessage,r),Object.assign(Object.assign({},t),{headers:{checkoutVariant:o}})))).pipe(M(e=>g(this.loadOrder(e.body.data.order.orderId,t),C(l(Mm.SubmitOrderSucceeded,e.body.data,Object.assign(Object.assign({},e.body.meta),{token:e.headers.token}))))))}).pipe(P(e=>Ke(Mm.SubmitOrderFailed,e))))}finalizeOrder(e,t){return g(C(l(Mm.FinalizeOrderRequested)),_(this._orderRequestSender.finalizeOrder(e,t)).pipe(M(n=>g(this.loadOrder(e,t),C(l(Mm.FinalizeOrderSucceeded,n.body.data)))))).pipe(P(e=>Ke(Mm.FinalizeOrderFailed,e)))}_getCurrentOrderId(e){const t=e.order.getOrder(),n=e.checkout.getCheckout();return t&&t.orderId||n&&n.orderId}_mapToOrderRequestBody(e,t,n,i){const{payment:r}=e,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]);return r?Object.assign(Object.assign({},o),{cartId:t,customerMessage:n,externalSource:i,payment:{paymentData:r.paymentData,name:r.methodId,gateway:r.gatewayId}}):Object.assign(Object.assign({},o),{cartId:t,customerMessage:n,externalSource:i})}}function Gm(e){const t=ke();return e.subscribe(e=>{const n=e.config.getStoreConfig();n&&t.setHost(n.paymentSettings.bigpayBaseUrl)},e=>e.config.getStoreConfig()),t}!function(e){e.LoadPaymentMethodRequested="LOAD_PAYMENT_METHOD_REQUESTED",e.LoadPaymentMethodSucceeded="LOAD_PAYMENT_METHOD_SUCCEEDED",e.LoadPaymentMethodFailed="LOAD_PAYMENT_METHOD_FAILED",e.LoadPaymentMethodsRequested="LOAD_PAYMENT_METHODS_REQUESTED",e.LoadPaymentMethodsSucceeded="LOAD_PAYMENT_METHODS_SUCCEEDED",e.LoadPaymentMethodsFailed="LOAD_PAYMENT_METHODS_FAILED"}(qm||(qm={}));const Hm=e=>!!e;class Wm{constructor(e){this._requestSender=e}loadPaymentMethodsById(e,t){return n=>new m(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodsRequested)),Promise.all(e.map(e=>{return n=this,i=void 0,o=function*(){try{return(yield this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a}))).body}catch(e){return}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).then(e=>{const t=e.filter(Hm);i.next(l(qm.LoadPaymentMethodsSucceeded,t)),i.complete()}).catch(e=>{i.next(l(qm.LoadPaymentMethodsFailed,e)),i.complete()})})}loadPaymentMethods(e){return t=>m.create(n=>{const i=t.getState().cart.getCartOrThrow();n.next(l(qm.LoadPaymentMethodsRequested)),this._requestSender.loadPaymentMethods(Object.assign(Object.assign({},e),{params:Object.assign(Object.assign({},null==e?void 0:e.params),{cartId:i.id})})).then(e=>{const t={deviceSessionId:e.headers["x-device-session-id"],sessionHash:e.headers["x-session-hash"]},i=e.body;n.next(l(qm.LoadPaymentMethodsSucceeded,i,t)),n.complete()}).catch(e=>{n.error(h(qm.LoadPaymentMethodsFailed,e))})})}loadPaymentMethod(e,t){return n=>m.create(i=>{var r;const o=null===(r=n.getState().cart.getCart())||void 0===r?void 0:r.id,a=o?Object.assign(Object.assign({},null==t?void 0:t.params),{cartId:o}):Object.assign({},null==t?void 0:t.params);i.next(l(qm.LoadPaymentMethodRequested,void 0,{methodId:e})),this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a})).then(t=>{i.next(l(qm.LoadPaymentMethodSucceeded,t.body,{methodId:e})),i.complete()}).catch(t=>{i.error(h(qm.LoadPaymentMethodFailed,t,{methodId:e}))})})}}!function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);o>3&&a&&Object.defineProperty(t,n,a)}([Ct],Wm.prototype,"loadPaymentMethod",null);class $m{constructor(e){this._requestSender=e}loadPaymentMethods({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/payments",{timeout:e,headers:Object.assign({Accept:lt.JsonV1,"X-API-INTERNAL":Tt},et),params:t})}loadPaymentMethod(e,{timeout:t,params:n}={}){const i=`/api/storefront/payments/${e}`;return this._requestSender.get(i,{timeout:t,headers:Object.assign({Accept:lt.JsonV1,"X-API-INTERNAL":Tt},et),params:n})}}class Ym extends rt{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var Km,Jm;!function(e){e.ExecuteFailed="PAYMENT_STRATEGY_EXECUTE_FAILED",e.ExecuteRequested="PAYMENT_STRATEGY_EXECUTE_REQUESTED",e.ExecuteSucceeded="PAYMENT_STRATEGY_EXECUTE_SUCCEEDED",e.FinalizeFailed="PAYMENT_STRATEGY_FINALIZE_FAILED",e.FinalizeRequested="PAYMENT_STRATEGY_FINALIZE_REQUESTED",e.FinalizeSucceeded="PAYMENT_STRATEGY_FINALIZE_SUCCEEDED",e.InitializeFailed="PAYMENT_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="PAYMENT_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="PAYMENT_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED"}(Km||(Km={})),function(e){e.ADYENV2="adyenv2",e.ADYENV2_GOOGLEPAY="googlepayadyenv2",e.ADYENV3="adyenv3",e.ADYENV3_GOOGLEPAY="googlepayadyenv3",e.AFFIRM="affirm",e.AFTERPAY="afterpay",e.AUTHORIZENET_GOOGLE_PAY="googlepayauthorizenet",e.AMAZONPAY="amazonpay",e.APPLEPAY="applepay",e.BLUESNAPV2="bluesnapv2",e.BOLT="bolt",e.CBA_MPGS="cba_mpgs",e.CHECKOUTCOM="checkoutcom",e.CHECKOUTCOM_APM="checkoutcomapm",e.CHECKOUTCOM_FAWRY="checkoutcomfawry",e.CHECKOUTCOM_SEPA="checkoutcomsepa",e.CHECKOUTCOM_IDEAL="checkoutcomideal",e.CREDIT_CARD="creditcard",e.CHECKOUTCOM_GOOGLE_PAY="googlepaycheckoutcom",e.CLEARPAY="clearpay",e.CONVERGE="converge",e.CYBERSOURCE="cybersource",e.CYBERSOURCEV2="cybersourcev2",e.BNZ="bnz",e.BNZ_GOOGLEPAY="googlepaybnz",e.CYBERSOURCEV2_GOOGLE_PAY="googlepaycybersourcev2",e.HUMM="humm",e.KLARNA="klarna",e.KLARNAV2="klarnav2",e.LEGACY="legacy",e.MOLLIE="mollie",e.MONERIS="moneris",e.NO_PAYMENT_DATA_REQUIRED="nopaymentdatarequired",e.OFFLINE="offline",e.OFFSITE="offsite",e.ORBITAL_GOOGLE_PAY="googlepayorbital",e.PAYPAL_EXPRESS="paypalexpress",e.PAYPAL_EXPRESS_CREDIT="paypalexpresscredit",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARD="paypalcommercecreditcards",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo",e.PPSDK="PAYMENT_TYPE_SDK",e.QUADPAY="quadpay",e.SAGE_PAY="sagepay",e.SQUARE="squarev2",e.STRIPEV3="stripev3",e.STRIPE_UPE="stripeupe",e.STRIPE_UPE_GOOGLE_PAY="googlepaystripeupe",e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISA_CHECKOUT="braintreevisacheckout",e.BRAINTREE_GOOGLE_PAY="googlepaybraintree",e.WE_PAY="wepay",e.WORLDPAYACCESS="worldpayaccess",e.WORLDPAYACCESS_GOOGLE_PAY="googlepayworldpayaccess",e.STRIPE_GOOGLE_PAY="googlepaystripe",e.SEZZLE="sezzle",e.ZIP="zip"}(Jm||(Jm={}));const Zm=Jm;class Qm{widgetInteraction(e,t){const n={methodId:t&&t.methodId};return g(C(l(Km.WidgetInteractionStarted,void 0,n)),f(()=>e().then(()=>l(Km.WidgetInteractionFinished,void 0,n)))).pipe(P(e=>Ke(Km.WidgetInteractionFailed,e,n)))}}class Xm{constructor(e,t,n,i,r){this._strategyRegistry=e,this._strategyRegistryV2=t,this._orderActionCreator=n,this._spamProtectionActionCreator=i,this._paymentIntegrationService=r,this._paymentStrategyWidgetActionCreator=new Qm}execute(e,t){const{payment:n={},useStoreCredit:i}=e,r={methodId:n.methodId};return o=>{const{checkout:a}=o.getState(),{shouldExecuteSpamCheck:s}=a.getCheckoutOrThrow();return g(s?this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(o):v(),C(l(Km.ExecuteRequested,void 0,r)),f(()=>{const a=o.getState();let s;if(a.payment.isPaymentDataRequired(i)){const e=a.paymentMethods.getPaymentMethod(n.methodId,n.gatewayId);if(!e)throw new ot(tt.MissingPaymentMethod);s=this._getStrategy(e)}else s=this._strategyRegistryV2.get({id:Zm.NO_PAYMENT_DATA_REQUIRED});return s.execute(e,Object.assign(Object.assign({},t),{methodId:n.methodId,gatewayId:n.gatewayId})).then(()=>l(Km.ExecuteSucceeded,void 0,r))})).pipe(P(e=>Ke(Km.ExecuteFailed,e,r)))}}finalize(e){const{integrations:t}=null!=e?e:{};return n=>g(C(l(Km.FinalizeRequested)),this._loadOrderPaymentsIfNeeded(n,e),f(()=>{return i=this,r=void 0,a=function*(){const i=n.getState(),{providerId:r="",gatewayId:o=""}=i.payment.getPaymentId()||{},a=i.paymentMethods.getPaymentMethod(r,o);if(!a)throw new Ym;let s;Qt(this._strategyRegistryV2,null!=t?t:[],this._paymentIntegrationService);try{s=this._getStrategy(a)}catch(e){throw new Ym}return yield s.finalize(Object.assign(Object.assign({},e),{methodId:a.id,gatewayId:a.gateway})),l(Km.FinalizeSucceeded,void 0,{methodId:a.id})},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>{const t=n.getState().payment.getPaymentId();return Ke(Km.FinalizeFailed,e,{methodId:t&&t.providerId})}))}initialize(e){const{methodId:t,gatewayId:n,integrations:i}=e;return r=>f(()=>{const o=r.getState(),a=o.paymentMethods.getPaymentMethod(t,n);if(!a)throw new ot(tt.MissingPaymentMethod);if(t&&o.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return v();Qt(this._strategyRegistryV2,null!=i?i:[],this._paymentIntegrationService);const s=this._getStrategy(a).initialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.InitializeRequested,void 0,{methodId:t,gatewayId:n})),s.then(()=>l(Km.InitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Ke(Km.InitializeFailed,e,{methodId:t,gatewayId:n})))}deinitialize(e){const{methodId:t,gatewayId:n}=e;return i=>f(()=>{const r=i.getState(),o=r.paymentMethods.getPaymentMethod(t,n);if(!o)throw new ot(tt.MissingPaymentMethod);if(t&&!r.paymentStrategies.isInitialized({methodId:t,gatewayId:n}))return v();const a=this._getStrategy(o).deinitialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:n}));return g(C(l(Km.DeinitializeRequested,void 0,{methodId:t,gatewayId:n})),a.then(()=>l(Km.DeinitializeSucceeded,void 0,{methodId:t,gatewayId:n})))}).pipe(P(e=>Ke(Km.DeinitializeFailed,e,{methodId:t,gatewayId:n})))}widgetInteraction(e,t){return this._paymentStrategyWidgetActionCreator.widgetInteraction(e,t)}_getStrategy(e){let t;try{t=this._strategyRegistry.getByMethod(e)}catch(n){try{t=this._strategyRegistryV2.get({id:e.id,gateway:e.gateway,type:e.type})}catch(t){throw wt().error(`[PaymentStrategyActionCreator] Unable to resolve V2 strategy for id: ${e.id}, gateway: ${e.gateway}, type: ${e.type}`),t}}return t}_loadOrderPaymentsIfNeeded(e,t){const n=e.getState().checkout.getCheckout();return n&&n.orderId?this._orderActionCreator.loadOrderPayments(n.orderId,t):v()}}class ey{isEqual(e,t){return Y(this._normalize(e),this._normalize(t))}_normalize(e){return{cartAmount:e.cartAmount,currency:e.currency,id:e.id,lineItems:{digitalItems:e.lineItems.digitalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId})),giftCertificates:e.lineItems.giftCertificates.slice().sort((e,t)=>`${e.id}`.localeCompare(`${t.id}`)).map(e=>({amount:e.amount,recipient:e.recipient})),physicalItems:e.lineItems.physicalItems.slice().sort((e,t)=>`${e.productId}${e.variantId}`.localeCompare(`${t.productId}${t.variantId}`)).map(e=>({extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId,giftWrapping:e.giftWrapping}))}}}}class ty extends rt{constructor(e,t){super("An update to your shopping cart has been detected and your available shipping costs have been updated."),this.name="CartChangedError",this.type="cart_changed",this.data={previous:e,updated:t}}}class ny{constructor(e){this._checkoutRequestSender=e}validate(e,t){if(!e)throw new ot(tt.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then(t=>{const n=new ey;if(!(e.outstandingBalance===t.body.outstandingBalance&&this._compareCoupons(e.coupons,t.body.coupons)&&this._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&n.isEqual(e.cart,t.body.cart)))throw new ty(this._getComparableCheckout(e),this._getComparableCheckout(t.body))})}_compareCoupons(e,t){return Y(oe(e,"code"),oe(t,"code"))}_compareGiftCertificates(e,t){return Y(oe(e,"code"),oe(t,"code"))}_getComparableCheckout(e){const{cart:t,coupons:n,giftCertificates:i,outstandingBalance:r}=e;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:n,giftCertificates:i,outstandingBalance:r}}}class iy{constructor(e){this._namespace=e}getItem(e){const t=Te.getItem(this.withNamespace(e));if(null===t)return null;try{return JSON.parse(t)}catch(t){return this.removeItem(this.withNamespace(e)),null}}getItemOnce(e){const t=this.getItem(e);return this.removeItem(e),t}setItem(e,t){return Te.setItem(this.withNamespace(e),JSON.stringify(t))}removeItem(e){return Te.removeItem(this.withNamespace(e))}withNamespace(e){return`${this._namespace}.${e}`}}class ry extends rt{constructor(){super("Please complete our human verification challenge and try again."),this.name="CardingProtectionChallengeNotCompletedError",this.type="carding_protection_challenge_not_completed"}}class oy extends rt{constructor(){super("We were not able to verify that you are not a robot. Please try again."),this.name="CardingProtectionFailedError",this.type="carding_protection_failed"}}var ay,sy,dy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class cy{constructor(e){this._googleRecaptcha=e}handle(e,t){return dy(this,void 0,void 0,function*(){return"string"==typeof e?this.handleWithRecaptchaSitekey(e,t):this.handleWithPaymentHumanVerificationRequestError(e)})}handleWithPaymentHumanVerificationRequestError(e){return dy(this,void 0,void 0,function*(){if(!this._isPaymentHumanVerificationRequest(e))throw e;return yield this._initialize(e.body.additional_action_required.data.key),this._performRecaptcha()})}handleWithRecaptchaSitekey(e,t){return dy(this,void 0,void 0,function*(){if("recaptcha_v2"!==e)throw Error("Human verification method is not supported.");if(!t)throw Error("Recaptcha site key is missing.");return yield this._initialize(t),this._performRecaptcha()})}_performRecaptcha(){return this._googleRecaptcha.execute().pipe(z(1)).pipe(M(({error:e,token:t})=>dy(this,void 0,void 0,function*(){if(e instanceof dn)throw new ry;if(e||!t)throw new oy;return{type:"recaptcha_v2_verification",data:{human_verification_token:t}}}))).toPromise()}_initialize(e){const t="cardingProtectionContainer";let n=document.getElementById(t);return n&&n.parentNode&&n.parentNode.removeChild(n),n=document.createElement("div"),n.setAttribute("id",t),document.body.appendChild(n),this._googleRecaptcha.load(t,e)}_isPaymentHumanVerificationRequest(e){const{additional_action_required:t,status:n}=e.body||{};return"additional_action_required"===n&&t&&"recaptcha_v2_verification"===t.type}}function ly(e,t){const{body:n}=e,{errors:i=[]}=n;return new Et(e,{message:uy(i)||t,errors:i})}function uy(e){if(Array.isArray(e))return e.reduce((e,t)=>t&&t.message?[...e,t.message]:e,[]).join(" ")}class hy extends rt{constructor(e){super(e||"Unable to proceed due to invalid configuration provided for the hosted payment form."),this.name="InvalidHostedFormConfigError",this.type="invalid_hosted_form_config"}}class py extends rt{constructor(e){super(e||"Unable to proceed due to an unknown error with the hosted payment form."),this.name="InvalidHostedFormError",this.type="invalid_hosted_form"}}class my extends rt{constructor(e){super(["Unable to proceed due to invalid user input values",...U(Ce(e),e=>oe(e,({message:e})=>e))].join(". ")),this.errors=e,this.name="InvalidHostedFormValueError",this.type="invalid_hosted_form_value"}}!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED",e.StoredCardRequested="HOSTED_FIELD:STORED_CARD_REQUESTED"}(ay||(ay={})),function(e){e.AttachSucceeded="HOSTED_INPUT:ATTACH_SUCCEEDED",e.AttachFailed="HOSTED_INPUT:ATTACH_FAILED",e.BinChanged="HOSTED_INPUT:BIN_CHANGED",e.Blurred="HOSTED_INPUT:BLURRED",e.Changed="HOSTED_INPUT:CHANGED",e.CardTypeChanged="HOSTED_INPUT:CARD_TYPE_CHANGED",e.Entered="HOSTED_INPUT:ENTERED",e.Focused="HOSTED_INPUT:FOCUSED",e.SubmitSucceeded="HOSTED_INPUT:SUBMIT_SUCCEEDED",e.SubmitFailed="HOSTED_INPUT:SUBMIT_FAILED",e.Validated="HOSTED_INPUT:VALIDATED",e.StoredCardSucceeded="HOSTED_INPUT:STORED_CARD_SUCCEEDED",e.StoredCardFailed="HOSTED_INPUT:STORED_CARD_FAILED"}(sy||(sy={}));var yy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class gy{constructor(e,t,n,i,r,o,a,s,d,c){this._type=e,this._containerId=t,this._placeholder=n,this._accessibilityLabel=i,this._styles=r,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=s,this._checkoutId=d,this._cardInstrument=c,this._iframe=document.createElement("iframe");const l=this._checkoutId?`/checkout/payment/hosted-field?version=1.904.2&checkoutId=${this._checkoutId}`:"/checkout/payment/hosted-field?version=1.904.2";this._iframe.src=l,this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}getType(){return this._type}attach(){return yy(this,void 0,void 0,function*(){const e=document.getElementById(this._containerId);if(!e)throw new hy("Unable to proceed because the provided container ID is not valid.");e.appendChild(this._iframe),this._eventListener.listen();const t=S(this._iframe,"load").pipe(M(({target:e})=>yy(this,void 0,void 0,function*(){const t=e&&e.contentWindow;if(!t)throw new Error("The content window of the iframe cannot be accessed.");this._eventPoster.setTarget(t),yield this._eventPoster.post({type:ay.AttachRequested,payload:{accessibilityLabel:this._accessibilityLabel,cardInstrument:this._cardInstrument,fontUrls:this._getFontUrls(),placeholder:this._placeholder,styles:this._styles,origin:document.location.origin,type:this._type}},{successType:sy.AttachSucceeded,errorType:sy.AttachFailed})})),z(1)).toPromise();yield this._detachmentObserver.ensurePresence([this._iframe],t)})}detach(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())}submitForm(e,t){return yy(this,void 0,void 0,function*(){try{const n=this._eventPoster.post({type:ay.SubmitRequested,payload:{fields:e,data:t}},{successType:sy.SubmitSucceeded,errorType:sy.SubmitFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],n)}catch(e){if(this._isSubmitErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new py(e.payload.error.message);if(e.payload.response)throw ly(e.payload.response);throw new Error(e.payload.error.message)}throw e}})}submitStoredCardForm(e,t){return yy(this,void 0,void 0,function*(){const n=this._eventPoster.post({type:ay.StoredCardRequested,payload:{fields:e,data:t}},{successType:sy.StoredCardSucceeded,errorType:sy.StoredCardFailed});return this._detachmentObserver.ensurePresence([this._iframe],n)})}validateForm(){return yy(this,void 0,void 0,function*(){const e=this._eventPoster.post({type:ay.ValidateRequested},{successType:sy.Validated}),{payload:t}=yield this._detachmentObserver.ensurePresence([this._iframe],e);if(!t.isValid)throw new my(t.errors)})}_getFontUrls(){const e="fonts.googleapis.com",t=document.querySelectorAll(`link[href*='${e}'][rel='stylesheet']`);return Array.prototype.slice.call(t).filter(t=>Cn(t.href).hostname===e).filter(e=>Ce(this._styles).map(e=>e&&e.fontFamily).filter(e=>"string"==typeof e).some(t=>t.split(/,\s/).some(t=>-1!==e.href.indexOf(t.replace(" ","+"))))).map(e=>e.href)}_isSubmitErrorEvent(e){return e.type===sy.SubmitFailed}}var fy,vy=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class _y{constructor(e,t,n,i,r){this._fields=e,this._eventListener=t,this._payloadTransformer=n,this._eventCallbacks=i,this._paymentHumanVerificationHandler=r,this._handleEnter=({payload:e})=>vy(this,void 0,void 0,function*(){try{yield this.validate()}catch(e){if(e instanceof Error&&"InvalidHostedFormValueError"!==e.name)throw e}const{onEnter:t=ce}=this._eventCallbacks;t(e)});const{onBlur:o=ce,onCardTypeChange:a=ce,onFocus:s=ce,onValidate:d=ce}=this._eventCallbacks;this._eventListener.addListener(sy.Blurred,({payload:e})=>o(e)),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>a(e)),this._eventListener.addListener(sy.Focused,({payload:e})=>s(e)),this._eventListener.addListener(sy.Validated,({payload:e})=>d(e)),this._eventListener.addListener(sy.Entered,this._handleEnter),this._eventListener.addListener(sy.CardTypeChanged,({payload:e})=>this._cardType=e.cardType),this._eventListener.addListener(sy.BinChanged,({payload:e})=>this._bin=e.bin)}getBin(){return this._bin}getCardType(){return this._cardType}attach(){return vy(this,void 0,void 0,function*(){this._eventListener.listen();const e=this._getFirstField(),t=be(this._fields,e);yield e.attach(),yield Promise.all(t.map(e=>e.attach()))})}detach(){this._eventListener.stopListen(),this._fields.forEach(e=>{e.detach()})}submit(e,t){return vy(this,void 0,void 0,function*(){try{return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,t))}catch(t){const n=yield this._paymentHumanVerificationHandler.handle(t);return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,n))}})}submitStoredCard(e){return vy(this,void 0,void 0,function*(){return this._getFirstField().submitStoredCardForm(e.fields,e.data)})}validate(){return vy(this,void 0,void 0,function*(){return this._getFirstField().validateForm()})}_getFirstField(){const e=this._fields[0];if(!e)throw new hy("Unable to proceed because the payment form has no field defined.");return e}}function Sy(e){return Boolean(e.instrumentId)}class Iy{constructor(e){this._store=e}transform(e,t){const n=this._store.getState(),i=n.checkout.getCheckout(),r=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),s=n.order.getOrderMeta(),d=le(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv");let c=n.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId);"worldpayaccess"===(null==c?void 0:c.gateway)&&"credit_card"===(null==c?void 0:c.id)&&(c=Object.assign(Object.assign({},c),{id:"worldpayaccess",method:"credit-card"}));const l=n.paymentMethods.getPaymentMethodsMeta(),u=o&&d&&Sy(d)?`${n.payment.getPaymentToken()}, ${o.vaultAccessToken}`:n.payment.getPaymentToken();if(!u)throw new ot(tt.MissingPaymentToken);return{additionalAction:t,authToken:u,checkout:i,config:r,order:a,orderMeta:s,payment:d,paymentMethod:c,paymentMethodMeta:l}}}class wy{constructor(e){this._store=e}create(e,t,n){const i=Object.keys(t.fields).reduce((i,r)=>{const o=t.fields[r];return o?[...i,new gy(r,o.containerId,o.placeholder||"",o.accessibilityLabel||"",t.styles||{},new On(e),new Kn(e),new Dn(new yn),n,"instrumentId"in o?this._getCardInstrument(o.instrumentId):void 0)]:i},[]);return new _y(i,new Kn(e),new Iy(this._store),pe(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new cy(Sn(o())))}_getCardInstrument(e){const{instruments:{getCardInstrument:t}}=this._store.getState(),n=t(e);if(!n)throw new ot(tt.MissingPaymentInstrument);return n}}!function(e){e.SubmitPaymentRequested="SUBMIT_PAYMENT_REQUESTED",e.SubmitPaymentSucceeded="SUBMIT_PAYMENT_SUCCEEDED",e.SubmitPaymentFailed="SUBMIT_PAYMENT_FAILED",e.InitializeOffsitePaymentRequested="INITIALIZE_OFFSITE_PAYMENT_REQUESTED",e.InitializeOffsitePaymentSucceeded="INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED",e.InitializeOffsitePaymentFailed="INITIALIZE_OFFSITE_PAYMENT_FAILED"}(fy||(fy={}));class Cy{constructor(e,t,n,i){this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=i,this.initializeOffsitePayment=({methodId:e,gatewayId:t,instrumentId:n,target:i,promise:r,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})=>s=>{let d;n?d={formattedPayload:{bigpay_token:n}}:o&&(d={formattedPayload:{vault_payment_instrument:o,set_as_default_stored_instrument:a||null}});const c=this._paymentRequestTransformer.transform({gatewayId:t,methodId:e,paymentData:d},s.getState());return g(C(l(fy.InitializeOffsitePaymentRequested)),Promise.race([this._paymentRequestSender.initializeOffsitePayment(c,i),r].filter(Boolean)).then(()=>l(fy.InitializeOffsitePaymentSucceeded))).pipe(P(e=>Ke(fy.InitializeOffsitePaymentFailed,e)))}}submitPayment(e){return t=>g(C(l(fy.SubmitPaymentRequested)),f(()=>{return n=this,i=void 0,o=function*(){try{return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,t.getState()))}catch(n){const i=yield this._paymentHumanVerificationHandler.handle(n);return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(Object.assign(Object.assign({},e),{additionalAction:i}),t.getState()))}},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}).pipe(M(({body:e})=>g(this._orderActionCreator.loadCurrentOrder()(t),C(l(fy.SubmitPaymentSucceeded,e)))))).pipe(P(e=>Ke(fy.SubmitPaymentFailed,e)))}}class by{constructor(e){this._client=e}submitPayment(e){return new Promise((t,n)=>{this._client.submitPayment(e,(e,i)=>{e?n(this._transformResponse(e)):t(this._transformResponse(i))})})}initializeOffsitePayment(e,t){return new Promise(()=>{this._client.initializeOffsitePayment(e,null,t)})}_transformResponse(e){return{headers:e.headers,body:e.data,status:e.status,statusText:e.statusText}}}function Py(e,t){let n;return function(e){return void 0!==e.id}(e)?n=e.id:t&&t.length&&(n=t[0].id),{id:n,firstName:e.firstName,lastName:e.lastName,company:e.company,addressLine1:e.address1,addressLine2:e.address2,city:e.city,province:e.stateOrProvince,provinceCode:e.stateOrProvinceCode,postCode:e.postalCode,country:e.country,countryCode:e.countryCode,phone:e.phone,customFields:e.customFields}}const Oy=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function Ey(e){return{code:e.code,discount:e.displayName,discountType:Oy.indexOf(e.couponType)}}function Ay(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function Ty(e){const t=[];return(e||[]).forEach(e=>{(e.banners||[]).forEach(e=>{t.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})})}),t}function ky(e,t,n="id"){return Object.keys(e).reduce((i,r)=>[...i,...e[r].map(e=>"giftCertificates"===r?function(e,t){const n=new vd(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:n.toInteger(e.amount),integerAmountAfterDiscount:n.toInteger(e.amount),integerUnitPrice:n.toInteger(e.amount),integerUnitPriceAfterDiscount:n.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,n,i="id"){const r=new vd(n);return{id:e[i],imageUrl:e.imageUrl,amount:e.extendedListPrice,amountAfterDiscount:e.extendedSalePrice,discount:e.discountAmount,integerAmount:r.toInteger(e.extendedListPrice),integerAmountAfterDiscount:r.toInteger(e.extendedSalePrice),integerDiscount:r.toInteger(e.discountAmount),integerUnitPrice:r.toInteger(e.listPrice),integerUnitPriceAfterDiscount:r.toInteger(e.salePrice),downloadsPageUrl:e.downloadPageUrl,name:e.name,quantity:e.quantity,brand:e.brand,sku:e.sku,categoryNames:e.categoryNames,variantId:e.variantId,productId:e.productId,attributes:(e.options||[]).map(e=>({name:e.name,value:e.value})),addedByPromotion:e.addedByPromotion,type:t}}(e,function(e){switch(e){case"physicalItems":return"ItemPhysicalEntity";case"digitalItems":return"ItemDigitalEntity";case"giftCertificates":return"ItemGiftCertificateEntity";default:return""}}(r),t,n))],[])}function Dy(e){const t=e.cart.currency.decimalPlaces,n=new vd(t);return{id:e.cart.id,items:ky(e.cart.lineItems,t),currency:e.cart.currency.code,coupon:{discountedAmount:ye(e.cart.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.cart.coupons.map(Ey)},discount:{amount:e.cart.discountAmount,integerAmount:n.toInteger(e.cart.discountAmount)},discountNotifications:Ty(e.promotions),giftCertificate:{totalDiscountedAmount:ye(e.giftCertificates,(e,t)=>e+t.used,0),appliedGiftCertificates:ne(e.giftCertificates.map(Ay),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:n.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:n.toInteger(e.shippingCostBeforeDiscount),required:fe(e.cart.lineItems.physicalItems,e=>e.isShippingRequired)},subtotal:{amount:e.subtotal,integerAmount:n.toInteger(e.subtotal)},storeCredit:{amount:e.customer?e.customer.storeCredit:0},taxSubtotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:n.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.grandTotal,integerAmount:n.toInteger(e.grandTotal)}}}var My;!function(e){e.APPLEPAY="applepay",e.AMAZON_PAY_V2="amazonpay",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_VENMO="braintreevenmo",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.GOOGLEPAY_ADYENV2="googlepayadyenv2",e.GOOGLEPAY_ADYENV3="googlepayadyenv3",e.GOOGLEPAY_AUTHORIZENET="googlepayauthorizenet",e.GOOGLEPAY_BNZ="googlepaybnz",e.GOOGLEPAY_BRAINTREE="googlepaybraintree",e.GOOGLEPAY_CHECKOUTCOM="googlepaycheckoutcom",e.GOOGLEPAY_CYBERSOURCEV2="googlepaycybersourcev2",e.GOOGLEPAY_ORBITAL="googlepayorbital",e.GOOGLEPAY_STRIPE="googlepaystripe",e.GOOGLEPAY_STRIPEUPE="googlepaystripeupe",e.GOOGLEPAY_WORLDPAYACCESS="googlepayworldpayaccess",e.PAYPALEXPRESS="paypalexpress"}(My||(My={}));const zy=My;function xy(e,t){const n=e.firstName||t.firstName||"",i=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map(e=>Py(e)),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:n,lastName:i,name:e.fullName||[n,i].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}class Ny{format(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*")),i=t.slice(0,2),r=4===n.length?n.slice(-2):n?n.slice(0,2):t.slice(2);return e.length<2?t:e.length>3&&!r?i:`${i} / ${r}`}toObject(e){const[t="",n=""]=e.split(new RegExp("\\s*/\\s*"));return/^\d+$/.test(t)&&/^\d+$/.test(n)?{month:1===t.length?`0${t}`:t.slice(0,2),year:2===n.length?`20${n}`:n.slice(0,4)}:{month:"",year:""}}}class Ry{format(e){const{card:t}=Me(e);if(!t)return e;const n=ae(De(e).map(e=>ae(e.lengths))),i=this.unformat(e).slice(0,n);return t.gaps.filter(e=>i.length>e).reduce((e,t,n)=>[e.slice(0,t+n),e.slice(t+n)].join(" "),i)}unformat(e){const{card:t}=Me(e);return t?e.replace(new RegExp(" ","g"),""):e}}function Fy(e,t={}){const n=e.currency.decimalPlaces,i=new vd(n);return{id:e.orderId,items:ky(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:By(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:i.toInteger(e.baseAmount)},coupon:{discountedAmount:ye(e.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.coupons.map(Ey)},discount:{amount:e.discountAmount,integerAmount:i.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:jy(e.payments),socialData:qy(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:Ly(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:i.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:i.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function Ly(e){const t=j(e,{providerId:"storecredit"});return t?t.amount:0}function jy(e){const t=L(e,{providerId:"giftcertificate"});return{totalDiscountedAmount:ye(t,(e,t)=>t.amount+e,0),appliedGiftCertificates:ne(t.map(e=>({code:e.detail.code,discountedAmount:e.amount,remainingBalance:e.detail.remaining,giftCertificate:{balance:e.amount+e.detail.remaining,code:e.detail.code,purchaseDate:""}})),"code")}}function By(e,t={}){const n=j(e,Uy);return n?{id:n.providerId,status:(i=n.detail.step,`PAYMENT_STATUS_${i}`),helpText:n.detail.instructions,returnUrl:t.returnUrl}:{};var i}function Uy(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function qy(e){const t={};return[...e.lineItems.physicalItems,...e.lineItems.digitalItems].forEach(e=>{var n;t[e.id]=(n=e,["fb","tw","gp"].reduce((e,t)=>{const i=n.socialMedia&&j(n.socialMedia,e=>e.code===t);return i?(e[t]={name:n.name,description:n.name,image:n.imageUrl,url:i.link,shareText:i.text,sharingLink:i.link,channelName:i.channel,channelCode:i.code},e):e},{}))}),t}function Vy(e,t){return{description:e.description,module:e.type,price:e.cost,id:e.id,selected:t,isRecommended:e.isRecommended,imageUrl:e.imageUrl,transitTime:e.transitTime}}class Gy{constructor(){this._cardExpiryFormatter=new Ny,this._cardNumberFormatter=new Ry}transform(e,t){const n=t.billingAddress.getBillingAddress(),i=t.checkout.getCheckout(),r=t.customer.getCustomer(),o=t.order.getOrder(),a=t.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),s=this._mapShippingAddress(t,a),d=t.consignments.getConsignments(),c=t.consignments.getShippingOption(),l=t.config.getStoreConfig(),u=t.config.getContextConfig(),h=t.instruments.getInstrumentsMeta(),p=t.paymentMethods.getPaymentMethodsMeta(),m=t.order.getOrderMeta(),y=r&&n&&xy(r,n),g=h&&e.paymentData&&(Sy(e.paymentData)||function(e){const t=e.formattedPayload;return!!t&&("string"==typeof t.bigpay_token||Boolean(t.bigpay_token&&t.bigpay_token.token))}(e.paymentData))?`${t.payment.getPaymentToken()}, ${h.vaultAccessToken}`:t.payment.getPaymentToken();if(!g)throw new ot(tt.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:g,customer:y,billingAddress:n&&Py(n),shippingAddress:s&&Py(s,d),shippingOption:c&&Vy(c,!0),cart:i&&Dy(i),order:o&&Fy(o,m),orderMeta:m,payment:e.paymentData,paymentMethod:a&&this._transformPaymentMethod(a),quoteMeta:{request:Object.assign(Object.assign({},p),{geoCountryCode:u&&u.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:pe(l&&l.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}transformWithHostedFormData(e,t,n){const{additionalAction:i,authToken:r,checkout:o,config:a,order:s,orderMeta:d,payment:c={},paymentMethod:l,paymentMethodMeta:u}=t,h=o&&o.consignments[0],p=h&&h.shippingAddress,m=h&&h.selectedShippingOption;return{additionalAction:i,authToken:r,paymentMethod:l&&this._transformPaymentMethod(l),customer:s&&s.billingAddress&&o&&xy(o.customer,s.billingAddress),billingAddress:s&&s.billingAddress&&Py(s.billingAddress),shippingAddress:p&&o&&Py(p,o.consignments),shippingOption:m&&Vy(m,!0),cart:o&&Dy(o),order:s&&Fy(s,d),orderMeta:d,payment:this._transformHostedInputValues(e,c,n),quoteMeta:{request:Object.assign(Object.assign({},u),{geoCountryCode:a&&a.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:a&&pe(a.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}_transformPaymentMethod(e){return"multi-option"!==e.method||e.gateway?e.initializationData&&e.initializationData.gateway?Object.assign(Object.assign({},e),{id:e.initializationData.gateway}):"worldpayaccess"===e.gateway&&"credit_card"===e.id?Object.assign(Object.assign({},e),{id:"worldpayaccess",method:"credit-card"}):e.id===zy.BRAINTREE_VENMO?Object.assign(Object.assign({},e),{id:zy.BRAINTREE_PAYPAL}):e:Object.assign(Object.assign({},e),{gateway:e.id})}_transformHostedInputValues(e,t,n){return"instrumentId"in t?Object.assign(Object.assign({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:n}):Object.assign(Object.assign({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:n})}_mapShippingAddress(e,t){var n,i,r,o;if(t){const a=null===(i=null===(n=t.initializationData)||void 0===n?void 0:n.bopis)||void 0===i?void 0:i.enabled,s=null===(o=null===(r=t.initializationData)||void 0===r?void 0:r.bopis)||void 0===o?void 0:o.requiredAddress,d=e.consignments.getConsignments(),c=null==d?void 0:d.every(e=>e.selectedPickupOption);if(a&&c&&"none"===s)return}return e.shippingAddress.getShippingAddress()}}const Hy=e=>{const{type:t,initializationStrategy:n}=e;return t===Zm.PPSDK&&"string"==typeof(null==n?void 0:n.type)};class Wy extends Gt{getByMethod(e){if(!e)return this.get();const t=this._getToken(e),n=[e.gateway,e.id].filter(e=>null!=e).join("-");return this.get(t,n)}_getToken(e){if(Hy(e))return Zm.PPSDK;if("klarna"===e.gateway)return Zm.KLARNAV2;const t=e.gateway||e.id;if(this._hasFactoryForMethod(t))return t;if("PAYMENT_TYPE_OFFLINE"===e.type)return Zm.OFFLINE;throw new Vt(`'${t}' is not registered.`)}_hasFactoryForMethod(e){return this._hasFactory(e)}}const $y="FINALIZE";class Yy extends Vt{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"}}var Ky=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n};class Jy{constructor(e,t,n,i){this._store=e,this._orderActionCreator=t,this._paymentActionCreator=n,this._hostedFormFactory=i}execute(e,t){var n,i;return this._isHostedPaymentFormEnabled(null===(n=e.payment)||void 0===n?void 0:n.methodId,null===(i=e.payment)||void 0===i?void 0:i.gatewayId)&&this._shouldRenderHostedForm?this._executeWithHostedForm(e,t):this._executeWithoutHostedForm(e,t)}finalize(e){return Promise.reject(new Ym)}initialize(e){if(!this._isHostedPaymentFormEnabled(null==e?void 0:e.methodId,null==e?void 0:e.gatewayId)||!this._isHostedFieldAvailable(e))return this._shouldRenderHostedForm=!1,Promise.resolve(this._store.getState());const t=e&&e.creditCard&&e.creditCard.form,{config:n}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:i=""}={}}=n.getStoreConfig()||{};if(!t)throw new Vt;const r=this._hostedFormFactory.create(i,t);return r.attach().then(()=>(this._shouldRenderHostedForm=!0,this._hostedForm=r,this._store.getState()))}deinitialize(e){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve(this._store.getState())}_executeWithoutHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=n&&n.paymentData;if(!n||!r)throw new Yy(["payment.paymentData"]);return this._store.dispatch(this._orderActionCreator.submitOrder(i,t)).then(()=>this._store.dispatch(this._paymentActionCreator.submitPayment(Object.assign(Object.assign({},n),{paymentData:r}))))}_executeWithHostedForm(e,t){const{payment:n}=e,i=Ky(e,["payment"]),r=this._hostedForm;if(!r)throw new gn(ln.PaymentNotInitialized);if(!n||!n.methodId)throw new Yy(["payment.methodId"]);return r.validate().then(()=>this._store.dispatch(this._orderActionCreator.submitOrder(i,t))).then(()=>r.submit(n)).then(()=>this._store.dispatch(this._orderActionCreator.loadCurrentOrder()))}_isHostedPaymentFormEnabled(e,t){if(!e)return!1;const{paymentMethods:{getPaymentMethodOrThrow:n}}=this._store.getState();return!0===n(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!Ce(e&&e.creditCard&&e.creditCard.form.fields).every(J)}}class Zy extends Jy{constructor(e,t,n,i,r){super(e,t,n,i),this._formPoster=r}execute(e,t){return super.execute(e,t).catch(e=>e instanceof Et&&fe(e.body.errors,{code:"three_d_secure_required"})?new Promise(()=>{this._formPoster.postForm(e.body.three_ds_result.acs_url,{PaReq:e.body.three_ds_result.payer_auth_request,TermUrl:e.body.three_ds_result.callback_url,MD:e.body.three_ds_result.merchant_data})}):Promise.reject(e))}finalize(e){const t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===$y?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Ym)}}class Qy extends rt{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}const Xy="redirecting";class eg{constructor(){this._isRedirecting=this.currentUrlHasRedirectingParam()}isRedirecting(){return this._isRedirecting}setRedirecting(e){e?this.setRedirectingParamOnUrl():this.removeRedirectingParamFromUrl(),this._isRedirecting=e}currentUrlHasRedirectingParam(){return Xy in this.getCurrentUrl().query}getCurrentUrl(){return xe(window.location.href)}replaceCurrentUrl(e){window.history.replaceState(null,"",e)}setRedirectingParamOnUrl(){if(this.currentUrlHasRedirectingParam())return;const e=this.getCurrentUrl(),t=Object.assign(Object.assign({},e),{query:Object.assign(Object.assign({},e.query),{[Xy]:"true"})});this.replaceCurrentUrl(Ne(t))}removeRedirectingParamFromUrl(){this.currentUrlHasRedirectingParam()&&this.replaceCurrentUrl(ze(window.location.href,[Xy]))}}const tg=he([e=>"continue"===V(e,"type")&&"redirect"===V(e,"code")&&(e=>{const t=V(e,"form_fields");return X(V(e,"url"))&&(ee(t)||Z(t))})(V(e,"parameters")),e=>"continue"===V(e,"type")&&"resubmit_with_human_verification"===V(e,"code")&&(e=>{const t=V(e,"available_methods");return W(t)})(V(e,"parameters"))]);class ng{constructor(e,t){this._formPoster=e,this._humanVerificationHandler=t}handle(e,t){switch(e.code){case"redirect":return(({url:e,form_fields:t},n)=>{const i=new eg;return i.isRedirecting()?(i.setRedirecting(!1),Promise.reject(new Qy)):(i.setRedirecting(!0),t?n.postForm(e,t):window.location.assign(e),new Promise(ce))})(e.parameters,this._formPoster);case"resubmit_with_human_verification":return(({available_methods:e},t,n)=>{return i=void 0,r=void 0,a=function*(){if(!n)throw new Error("PPSDK human verification callback function is missing.");if(!t)throw new Error("PPSDK human verification handler is missing.");if(0===e.length)throw Error("Human verification method is missing.");const{id:i,parameters:r}=e[0],o=yield t.handle(i,r.key);return n(o)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})(e.parameters,this._humanVerificationHandler,null==t?void 0:t.humanVerification)}}}class ig{constructor(e){this._continueHandler=e}handle(e,t){const{body:n}=e;return(e=>"success"===V(e,"type"))(n)?Promise.resolve():(e=>tg(e))(n)?this._continueHandler.handle(n,null==t?void 0:t.continue):(e=>"failure"===V(e.body,"type")&&X(V(e.body,"code")))(e)?(e=>{return Promise.reject(new Et((t=e,Object.assign(Object.assign({},t),{body:{errors:[{code:t.body.code}]}}))));var t})(e):((e=>{V(e.body,"type")})(e),(e=>Promise.reject(new Et(e)))(e))}}const rg="completed-payments";class og{constructor(e){this._browserStorage=e}isCompleted(e){return this.getCompletedPayments().indexOf(e)>=0}setCompleted(e){const t=this.getCompletedPayments();t.push(e),this.setCompletedPayments(t)}getCompletedPayments(){return this._browserStorage.getItem(rg)||[]}setCompletedPayments(e){this._browserStorage.setItem(rg,e)}}var ag,sg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class dg{constructor(e,t,n,i,r){this._store=e,this._orderActionCreator=t,this._subStrategyRegistry=n,this._paymentResumer=i,this._completedPayments=new og(r)}execute(e,t){var n;return sg(this,void 0,void 0,function*(){const{bigpayBaseUrl:i}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==t?void 0:t.methodId))throw new Vt('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:r}=t,{payment:o}=e,a=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["payment"]),{_subStrategy:s}=this;if(!s)throw new gn(ln.PaymentNotInitialized);yield this._store.dispatch(this._orderActionCreator.submitOrder(a,t));const d=null===(n=this._store.getState().order.getOrderMeta())||void 0===n?void 0:n.token;if(!d)throw new ot(tt.MissingOrder);return yield s.execute({methodId:r,payment:o,bigpayBaseUrl:i,token:d}),this._store.getState()})}finalize(e){return sg(this,void 0,void 0,function*(){const t=this._store.getState().order.getOrderOrThrow();if(t.isComplete)return this._store.getState();const{bigpayBaseUrl:n}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==e?void 0:e.methodId))throw new Vt('Unable to submit payment because "options.methodId" argument is not provided.');const i=this._store.getState().order.getPaymentId(e.methodId);if(!i||!t||this._completedPayments.isCompleted(i))throw new Ym;const{orderId:r}=t;return yield this._paymentResumer.resume({paymentId:i,bigpayBaseUrl:n,orderId:r}).catch(e=>{throw this._completedPayments.setCompleted(i),e}),this._store.getState()})}initialize(e){return sg(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new Vt('Unable to submit payment because "options.methodId" argument is not provided.');const t=((e,t)=>{const n=e.getState().paymentMethods.getPaymentMethod(t);if(n&&Hy(n))return n})(this._store,e.methodId);if(!t)throw new gn(ln.PaymentNotInitialized);if(this._subStrategy=this._subStrategyRegistry.getByMethod(t),!this._subStrategy)throw new gn(ln.PaymentNotInitialized);return yield this._subStrategy.initialize(e),this._store.getState()})}deinitialize(e){var t;return sg(this,void 0,void 0,function*(){return null===(t=this._subStrategy)||void 0===t||t.deinitialize(),this._store.getState()})}}!function(e){e.CARD="card_ui",e.NONE="none",e.UNSUPPORTED="unsupported"}(ag||(ag={}));const cg=x([[e=>"card_ui"===e.type,N(ag.CARD)],[e=>"none"===e.type,N(ag.NONE)],[ve,N(ag.UNSUPPORTED)]]);class lg extends Gt{getByMethod(e){const t=cg(e.initializationStrategy);return this.get(t)}}var ug=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class hg{constructor(e,t,n,i){this._store=e,this._orderActionCreator=t,this._hostedFormFactory=n,this._ppsdkStepHandler=i}execute(e){return ug(this,void 0,void 0,function*(){const t=this._hostedForm;if(!t)throw new gn(ln.PaymentNotInitialized);const{additionalAction:n,payment:i}=e;if(!i||!i.methodId)throw new Yy(["payment.methodId"]);yield t.validate();const{payload:r}=yield t.submit(i,n),{response:o}=r;yield this._ppsdkStepHandler.handle(o,{continue:{humanVerification:t=>ug(this,void 0,void 0,function*(){return this.execute(Object.assign({additionalAction:t},e))})}}),yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder())})}initialize(e){return ug(this,void 0,void 0,function*(){const t=e&&e.creditCard&&e.creditCard.form,{config:n,checkout:i}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:r=""}={}}=n.getStoreConfig()||{},o=i.getCheckoutOrThrow().id;if(!t)throw new Vt;const a=t&&this._hostedFormFactory.create(r,t,o);yield a.attach(),this._hostedForm=a})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}class pg{constructor(e,t){this._requestSender=e,this._stepHandler=t}execute({methodId:e,bigpayBaseUrl:t,token:n}){const i={credentials:!1,body:{payment_method_id:e},headers:{authorization:n,"X-XSRF-TOKEN":null}};return this._requestSender.post(`${t}/payments`,i).then(e=>this._stepHandler.handle(e))}initialize(){return Promise.resolve()}deinitialize(){}}var mg,yg,gg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class fg{constructor(e,t){this._requestSender=e,this._stepHandler=t}resume({paymentId:e,bigpayBaseUrl:t,orderId:n}){return gg(this,void 0,void 0,function*(){const i={credentials:!1,headers:{authorization:yield this._getToken(n).catch(()=>{throw new Ym}),"X-XSRF-TOKEN":null}};return this._requestSender.get(`${t}/payments/${e}`,i).then(e=>this._stepHandler.handle(e))})}_getToken(e){return gg(this,void 0,void 0,function*(){const t={params:{order_id:e}};return this._requestSender.get("/api/storefront/payments/auth-token",t).then(({body:e})=>e.auth_token)})}}class vg extends Jy{constructor(e,t,n,i,r){super(e,t,n,i),this._wepayRiskClient=r}initialize(e){return this._wepayRiskClient.initialize(),super.initialize(e)}execute(e,t){const n=this._wepayRiskClient.getRiskToken(),i=de({},e,{payment:{paymentData:{deviceSessionId:n}}});return super.execute(i,t)}}class _g{constructor(e){this._scriptLoader=e}initialize(){return this._scriptLoader.loadScript("//static.wepay.com/min/js/risk.1.latest.js").then(()=>this._riskClient=window.WePay.risk).then(()=>this)}getRiskToken(){if(!this._riskClient)throw new gn(ln.PaymentNotInitialized);return this._riskClient.generate_risk_token(),this._riskClient.get_risk_token()}}class Sg{constructor(e){this._requestSender=e}createBuyNowCart(e,{timeout:t}={}){const n=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post("/api/storefront/carts",{body:e,headers:n,timeout:t})}}!function(e){e.UpdatePaymentProviderCustomer="UPDATE_PAYMENT_PROVIDER_CUSTOMER"}(mg||(mg={}));class Ig{updatePaymentProviderCustomer(e){return C(l(mg.UpdatePaymentProviderCustomer,e))}}!function(e){e.ForgetCheckoutRemoteCustomerRequested="FORGET_CHECKOUT_REMOTE_CUSTOMER_REQUESTED",e.ForgetCheckoutRemoteCustomerSucceeded="FORGET_CHECKOUT_REMOTE_CUSTOMER_SUCCEEDED",e.ForgetCheckoutRemoteCustomerFailed="FORGET_CHECKOUT_REMOTE_CUSTOMER_FAILED",e.InitializeRemoteBillingRequested="INITIALIZE_REMOTE_BILLING_REQUESTED",e.InitializeRemoteBillingSucceeded="INITIALIZE_REMOTE_BILLING_SUCCEEDED",e.InitializeRemoteBillingFailed="INITIALIZE_REMOTE_BILLING_FAILED",e.InitializeRemoteShippingRequested="INITIALIZE_REMOTE_SHIPPING_REQUESTED",e.InitializeRemoteShippingSucceeded="INITIALIZE_REMOTE_SHIPPING_SUCCEEDED",e.InitializeRemoteShippingFailed="INITIALIZE_REMOTE_SHIPPING_FAILED",e.InitializeRemotePaymentRequested="INITIALIZE_REMOTE_PAYMENT_REQUESTED",e.InitializeRemotePaymentSucceeded="INITIALIZE_REMOTE_PAYMENT_SUCCEEDED",e.InitializeRemotePaymentFailed="INITIALIZE_REMOTE_PAYMENT_FAILED",e.LoadRemoteSettingsRequested="LOAD_REMOTE_SETTINGS_REQUESTED",e.LoadRemoteSettingsSucceeded="LOAD_REMOTE_SETTINGS_SUCCEEDED",e.LoadRemoteSettingsFailed="LOAD_REMOTE_SETTINGS_FAILED",e.SignOutRemoteCustomerRequested="SIGN_OUT_REMOTE_CUSTOMER_REQUESTED",e.SignOutRemoteCustomerSucceeded="SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED",e.SignOutRemoteCustomerFailed="SIGN_OUT_REMOTE_CUSTOMER_FAILED",e.UpdateRemoteCheckout="UPDATE_REMOTE_CHECKOUT"}(yg||(yg={}));var wg;class Cg{constructor(e,t){this._remoteCheckoutRequestSender=e,this._checkoutActionCreator=t}initializeBilling(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteBillingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeBilling(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteBillingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteBillingFailed,t,{methodId:e}))})})}initializeShipping(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemoteShippingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeShipping(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemoteShippingSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemoteShippingFailed,t,{methodId:e}))})})}initializePayment(e,t,n){return m.create(i=>{i.next(l(yg.InitializeRemotePaymentRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializePayment(e,t,n).then(({body:t={}})=>{i.next(l(yg.InitializeRemotePaymentSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(yg.InitializeRemotePaymentFailed,t,{methodId:e}))})})}loadSettings(e,t){return m.create(n=>{n.next(l(yg.LoadRemoteSettingsRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.loadSettings(e,t).then(({body:t})=>{n.next(l(yg.LoadRemoteSettingsSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.LoadRemoteSettingsFailed,t,{methodId:e}))})})}signOut(e,t){return m.create(n=>{n.next(l(yg.SignOutRemoteCustomerRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.signOut(e,t).then(()=>{n.next(l(yg.SignOutRemoteCustomerSucceeded,void 0,{methodId:e})),n.complete()}).catch(t=>{n.error(h(yg.SignOutRemoteCustomerFailed,t,{methodId:e}))})})}forgetCheckout(e,t){return g(C(l(yg.ForgetCheckoutRemoteCustomerRequested,void 0,{methodId:e})),f(()=>{return n=this,i=void 0,o=function*(){return yield this._remoteCheckoutRequestSender.forgetCheckout(t),yield this._checkoutActionCreator.loadCurrentCheckout(),l(yg.ForgetCheckoutRemoteCustomerSucceeded,void 0,{methodId:e})},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(t=>Ke(yg.ForgetCheckoutRemoteCustomerFailed,t,{methodId:e})))}updateCheckout(e,t){return l(yg.UpdateRemoteCheckout,t,{methodId:e})}}class bg{constructor(e){this._requestSender=e}initializeBilling(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/billing`;return this._requestSender.get(i,{params:t,timeout:n,headers:et})}initializeShipping(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/shipping`;return this._requestSender.get(i,{params:t,timeout:n,headers:et})}initializePayment(e,t,{timeout:n}={}){const i=`/remote-checkout/${e}/payment`;return this._requestSender.get(i,{params:t,timeout:n,headers:et})}loadSettings(e,{timeout:t}={}){const n=`/remote-checkout/${e}/settings`;return this._requestSender.get(n,{timeout:t,headers:et})}signOut(e,{timeout:t}={}){const n=`/remote-checkout/${e}/signout`;return this._requestSender.get(n,{timeout:t,headers:et})}generateToken({timeout:e}={}){return this._requestSender.get("/remote-checkout-token",{timeout:e,headers:et})}trackAuthorizationEvent({timeout:e}={}){return this._requestSender.post("/remote-checkout/events/shopper-checkout-service-provider-authorization-requested",{timeout:e,headers:et})}forgetCheckout({timeout:e}={}){return this._requestSender.post("/remote-checkout/forget-checkout",{timeout:e,headers:et})}}!function(e){e.CreateConsignmentsRequested="CREATE_CONSIGNMENTS_REQUESTED",e.CreateConsignmentsSucceeded="CREATE_CONSIGNMENTS_SUCCEEDED",e.CreateConsignmentsFailed="CREATE_CONSIGNMENTS_FAILED",e.UpdateConsignmentRequested="UPDATE_CONSIGNMENT_REQUESTED",e.UpdateConsignmentSucceeded="UPDATE_CONSIGNMENT_SUCCEEDED",e.UpdateConsignmentFailed="UPDATE_CONSIGNMENT_FAILED",e.DeleteConsignmentRequested="DELETE_CONSIGNMENT_REQUESTED",e.DeleteConsignmentSucceeded="DELETE_CONSIGNMENT_SUCCEEDED",e.DeleteConsignmentFailed="DELETE_CONSIGNMENT_FAILED",e.UpdateShippingOptionRequested="UPDATE_SHIPPING_OPTION_REQUESTED",e.UpdateShippingOptionSucceeded="UPDATE_SHIPPING_OPTION_SUCCEEDED",e.UpdateShippingOptionFailed="UPDATE_SHIPPING_OPTION_FAILED",e.LoadShippingOptionsRequested="LOAD_SHIPPING_OPTIONS_REQUESTED",e.LoadShippingOptionsSucceeded="LOAD_SHIPPING_OPTIONS_SUCCEEDED",e.LoadShippingOptionsFailed="LOAD_SHIPPING_OPTIONS_FAILED"}(wg||(wg={}));class Pg{constructor(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}unassignItemsByAddress(e,t){return n=>{const i=n.getState();if(!i.checkout.getCheckout())throw new ot(tt.MissingCheckout);const r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);if(!o)throw new Vt("No consignment found for the specified address");const a=this._removeLineItems(e.lineItems,o,i.cart.getCart());return a.length?this.updateConsignment({id:o.id,address:r,lineItems:a},t)(n):this.deleteConsignment(o.id,t)(n)}}assignItemsByAddress(e,t){return n=>{const i=n.getState(),r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=i.consignments.getConsignmentByAddress(r);return this._createOrUpdateConsignment({id:o&&o.id,address:r,lineItems:this._addLineItems(e.lineItems,o,i.cart.getCart())},t)(n)}}selectShippingOption(e,t){return n=>m.create(i=>{const r=n.getState(),o=r.checkout.getCheckout(),a=r.consignments.getConsignments();if(!o)throw new ot(tt.MissingCheckout);if(!a||!a.length)throw new ot(tt.MissingConsignments);const s={id:a[0].id,shippingOptionId:e},d={id:a[0].id};i.next(l(wg.UpdateShippingOptionRequested,void 0,d)),this._consignmentRequestSender.updateConsignment(o.id,s,t).then(({body:e})=>{i.next(l(wg.UpdateShippingOptionSucceeded,e,d)),i.complete()}).catch(e=>{i.error(h(wg.UpdateShippingOptionFailed,e,d))})})}loadShippingOptions(e){return t=>m.create(n=>{const i=t.getState().checkout.getCheckout();if(!i)throw new ot(tt.MissingCheckout);n.next(l(wg.LoadShippingOptionsRequested)),this._checkoutRequestSender.loadCheckout(i.id,Object.assign(Object.assign({},e),{params:{include:[xt.AvailableShippingOptions]}})).then(({body:e})=>{n.next(l(wg.LoadShippingOptionsSucceeded,e)),n.complete()}).catch(e=>{n.error(h(wg.LoadShippingOptionsFailed,e))})})}updateAddress(e,t){return n=>{const i=this._getUpdateAddressRequestBody(e,n),r=n.getState().consignments.getConsignments();return r&&r.length&&(i.id=r[0].id),this._createOrUpdateConsignment(i,t)(n)}}createConsignments(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new ot(tt.MissingCheckout);i.next(l(wg.CreateConsignmentsRequested)),this._consignmentRequestSender.createConsignments(r.id,e,t).then(({body:e})=>{i.next(l(wg.CreateConsignmentsSucceeded,e)),i.complete()}).catch(e=>{i.error(h(wg.CreateConsignmentsFailed,e))})})}updateConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout();if(!r||!r.id)throw new ot(tt.MissingCheckout);const o={id:e.id};i.next(l(wg.UpdateConsignmentRequested,void 0,o)),this._consignmentRequestSender.updateConsignment(r.id,e,t).then(({body:e})=>{i.next(l(wg.UpdateConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(wg.UpdateConsignmentFailed,e,o))})})}deleteConsignment(e,t){return n=>m.create(i=>{const r=n.getState().checkout.getCheckout(),o={id:e};if(!r||!r.id)throw new ot(tt.MissingCheckout);i.next(l(wg.DeleteConsignmentRequested,void 0,o)),this._consignmentRequestSender.deleteConsignment(r.id,e,t).then(({body:e})=>{i.next(l(wg.DeleteConsignmentSucceeded,e,o)),i.complete()}).catch(e=>{i.error(h(wg.DeleteConsignmentFailed,e,o))})})}updateShippingOption(e,t){return n=>m.create(i=>{var r;const o=n.getState().checkout.getCheckout(),a=n.getState().consignments.getConsignmentById(e.id);if((null===(r=null==a?void 0:a.selectedShippingOption)||void 0===r?void 0:r.id)===e.shippingOptionId)return void i.complete();if(!o||!o.id)throw new ot(tt.MissingCheckout);const s={id:e.id};i.next(l(wg.UpdateShippingOptionRequested,void 0,s)),this._consignmentRequestSender.updateConsignment(o.id,e,t).then(({body:e})=>{i.next(l(wg.UpdateShippingOptionSucceeded,e,s)),i.complete()}).catch(e=>{i.error(h(wg.UpdateShippingOptionFailed,e,s))})})}_createOrUpdateConsignment(e,t){return n=>{const i=n.getState().checkout.getCheckout();if(!i||!i.id)throw new ot(tt.MissingCheckout);return this._isUpdateConsignmentRequest(e)?this.updateConsignment(e,t)(n):this.createConsignments([e],t)(n)}}_getUpdateAddressRequestBody(e,t){const n=t.getState().cart.getCart();if(!n)throw new ot(tt.MissingCart);const{physicalItems:i,customItems:r=[]}=n.lineItems;return{address:e,lineItems:[...i,...r].map(e=>({itemId:e.id,quantity:e.quantity}))}}_removeLineItems(e,t,n){if(!n)throw new ot(tt.MissingCart);return this._hydrateLineItems(t.lineItemIds,n).map(t=>{const n=j(e,e=>e.itemId===t.itemId);return Object.assign(Object.assign({},t),{quantity:n?t.quantity-n.quantity:t.quantity})}).filter(e=>e.quantity>0)}_addLineItems(e,t,n){if(!t)return e;if(!n)throw new ot(tt.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,n)).filter(e=>e.quantity>0)}_hydrateLineItems(e,t){return e.map(e=>{const n=j(t.lineItems.physicalItems,t=>t.id===e);return{itemId:e,quantity:n?n.quantity:0}})}_isUpdateConsignmentRequest(e){return!!e.id}_consignmentHasAddress(e){return"object"==typeof e&&"address"in e}}const Og=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"];class Eg{constructor(e){this._requestSender=e}createConsignments(e,t,{timeout:n,params:{include:i}={}}={}){const r=`/api/storefront/checkouts/${e}/consignments`,o=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(r,{body:t,params:{include:en(Og,i)},headers:o,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}updateConsignment(e,t,{timeout:n,params:{include:i}={}}={}){const{id:r}=t,o=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["id"]),a=`/api/storefront/checkouts/${e}/consignments/${r}`,s=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.put(a,{body:o,params:{include:en(Og,i)},headers:s,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}deleteConsignment(e,t,{timeout:n}={}){const i=`/api/storefront/checkouts/${e}/consignments/${t}`,r=Object.assign({Accept:lt.JsonV1},et),o=Lt(Og);return this._requestSender.delete(i,{params:{include:o},headers:r,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new ct;throw e})}}var Ag,Tg;!function(e){e.LoadShippingCountriesRequested="LOAD_SHIPPING_COUNTRIES_REQUESTED",e.LoadShippingCountriesSucceeded="LOAD_SHIPPING_COUNTRIES_SUCCEEDED",e.LoadShippingCountriesFailed="LOAD_SHIPPING_COUNTRIES_FAILED"}(Ag||(Ag={}));class kg{constructor(e,t){this._shippingCountryRequestSender=e,this._store=t}loadCountries(e){const{checkout:t}=this._store.getState(),n=t.getCheckout(),i=n?n.channelId:null;return m.create(t=>{t.next(l(Ag.LoadShippingCountriesRequested)),this._shippingCountryRequestSender.loadCountries(i,e).then(e=>{t.next(l(Ag.LoadShippingCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Ag.LoadShippingCountriesFailed,e))})})}}class Dg{constructor(e,t){this._requestSender=e,this._config=t}loadCountries(e,{timeout:t}={}){const n="/internalapi/v1/shipping/countries"+(e?`?channel_id=${e}`:""),i=Object.assign({"Accept-Language":this._config.locale},et);return this._requestSender.get(n,{headers:i,timeout:t})}}!function(e){e.ApplyStoreCreditRequested="APPLY_STORE_CREDIT_REQUESTED",e.ApplyStoreCreditSucceeded="APPLY_STORE_CREDIT_SUCCEEDED",e.ApplyStoreCreditFailed="APPLY_STORE_CREDIT_FAILED"}(Tg||(Tg={}));var Mg;class zg{constructor(e){this._storeCreditRequestSender=e}applyStoreCredit(e,t){return n=>g(C(l(Tg.ApplyStoreCreditRequested)),f(()=>{return i=this,r=void 0,a=function*(){var i;const r=n.getState().checkout.getCheckout();if(!r)throw new ot(tt.MissingCheckout);const{id:o}=r,a=null!==(i=null==t?void 0:t.version)&&void 0!==i?i:r.version,{body:s}=yield e?this._storeCreditRequestSender.applyStoreCredit(o,Object.assign(Object.assign({},t),{version:a})):this._storeCreditRequestSender.removeStoreCredit(o,Object.assign(Object.assign({},t),{version:a}));return l(Tg.ApplyStoreCreditSucceeded,s)},new((o=void 0)||(o=Promise))(function(e,t){function n(e){try{d(a.next(e))}catch(e){t(e)}}function s(e){try{d(a.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof o?i:new o(function(e){e(i)})).then(n,s)}d((a=a.apply(i,r||[])).next())});var i,r,o,a})).pipe(P(e=>Ke(Tg.ApplyStoreCreditFailed,e)))}}class xg{constructor(e){this._requestSender=e}applyStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post(i,{headers:r,timeout:t,params:{include:Lt(zt)},body:{version:n}})}removeStoreCredit(e,{timeout:t,version:n}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,r=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.delete(i,{headers:r,timeout:t,params:{include:Lt(zt)},body:{version:n}})}}!function(e){e.UpdateSubscriptionsRequested="UPDATE_SUBSCRIPTIONS_REQUESTED",e.UpdateSubscriptionsSucceeded="UPDATE_SUBSCRIPTIONS_SUCCEEDED",e.UpdateSubscriptionsFailed="UPDATE_SUBSCRIPTIONS_FAILED"}(Mg||(Mg={}));class Ng extends Et{constructor(e){super(e),this.name="UpdateSubscriptionsError",this.type="update_subscriptions"}}class Rg{constructor(e){this._subscriptionsRequestSender=e}updateSubscriptions(e,t){return g(C(l(Mg.UpdateSubscriptionsRequested)),f(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._subscriptionsRequestSender.updateSubscriptions(e,t);return l(Mg.UpdateSubscriptionsSucceeded,n)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Ke(Mg.UpdateSubscriptionsFailed,new Ng(e))))}}class Fg{constructor(e){this._requestSender=e}updateSubscriptions(e,{timeout:t}={}){const n=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:n,timeout:t})}}function Lg(e){return Q(e)}const jg=se(e=>Array.isArray(e)?e.map(e=>Bg(e)):Lg(e)?Object.keys(e).reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:Bg(e[n])}),{}):e);jg.cache=new WeakMap;const Bg=e=>"object"==typeof e&&null!==e?jg(e):e;function Ug(e){return(...t)=>Bg(e(...t))}function qg({billingAddress:{getBillingAddress:e,getBillingAddressOrThrow:t},cart:{getCart:n,getCartOrThrow:i,getLocale:r},checkout:{getCheckout:o,getCheckoutOrThrow:a,getOutstandingBalance:s},config:{getContextConfig:d,getHost:c,getLocale:l,getStoreConfig:u,getStoreConfigOrThrow:h,getConfig:p},consignments:{getConsignments:m,getConsignmentsOrThrow:y},countries:{getCountries:g},customer:{getCustomer:f,getCustomerOrThrow:v},instruments:{getCardInstrument:_,getCardInstrumentOrThrow:S,getInstruments:I,getInstrumentsMeta:w},order:{getOrder:C,getOrderOrThrow:b,getOrderMeta:P},payment:{getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,isPaymentDataRequired:x},paymentMethods:{getPaymentMethod:N,getPaymentMethodOrThrow:R,getPaymentMethodsMeta:F},paymentProviderCustomer:{getPaymentProviderCustomer:L,getPaymentProviderCustomerOrThrow:j},paymentStrategies:{isInitialized:B},shippingAddress:{getShippingAddress:U,getShippingAddressOrThrow:q,getShippingAddresses:V,getShippingAddressesOrThrow:G},shippingCountries:{getShippingCountries:H}}){return{getHost:Ug(c),getLocale:Ug(l),getCartLocale:Ug(r),getBillingAddress:Ug(e),getBillingAddressOrThrow:Ug(t),getCart:Ug(n),getCartOrThrow:Ug(i),getCheckout:Ug(o),getCheckoutOrThrow:Ug(a),getCountries:Ug(g),getStoreConfig:Ug(u),getStoreConfigOrThrow:Ug(h),getConfig:Ug(p),getConsignments:Ug(m),getConsignmentsOrThrow:Ug(y),getContextConfig:Ug(d),getCustomer:Ug(f),getCustomerOrThrow:Ug(v),getCardInstrument:Ug(_),getInstruments:Ug(I),getCardInstrumentOrThrow:Ug(S),getOrder:Ug(C),getOrderOrThrow:Ug(b),getOrderMeta:Ug(P),getInstrumentsMeta:Ug(w),getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,getPaymentMethod:Ug(N),getPaymentMethodOrThrow:Ug(R),getPaymentMethodsMeta:Ug(F),getPaymentProviderCustomer:Ug(L),getPaymentProviderCustomerOrThrow:Ug(j),getShippingAddress:Ug(U),getShippingAddressOrThrow:Ug(q),getShippingAddresses:Ug(V),getShippingAddressesOrThrow:Ug(G),getShippingCountries:Ug(H),getOutstandingBalance:Ug(s),isPaymentDataRequired:x,isPaymentMethodInitialized:B}}var Vg,Gg=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class Hg{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,f,v,_){this._store=e,this._storeProjectionFactory=t,this._checkoutActionCreator=n,this._checkoutValidator=i,this._hostedFormFactory=r,this._orderActionCreator=o,this._billingAddressActionCreator=a,this._consignmentActionCreator=s,this._paymentMethodActionCreator=d,this._paymentActionCreator=c,this._paymentHumanVerificationHandler=l,this._customerActionCreator=u,this._cartRequestSender=h,this._storeCreditActionCreator=p,this._couponActionCreator=m,this._spamProtectionActionCreator=y,this._paymentProviderCustomerActionCreator=g,this._shippingCountryActionCreator=f,this._remoteCheckoutActionCreator=v,this._paymentStrategyWidgetActionCreator=_,this._storeProjection=this._storeProjectionFactory.create(this._store)}createHostedForm(e,t){const n=this._storeProjection.getState().getCheckoutOrThrow().id;return this._hostedFormFactory.create(e,t,n)}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}getState(){return this._storeProjection.getState()}initializeOffsitePayment(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.initializeOffsitePayment(e)),this._storeProjection.getState()})}loadCheckout(e){return Gg(this,void 0,void 0,function*(){return e?yield this._store.dispatch(this._checkoutActionCreator.loadCheckout(e)):yield this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),this._storeProjection.getState()})}loadDefaultCheckout(){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()),this._storeProjection.getState()})}loadPaymentMethod(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e,t)),this._storeProjection.getState()})}loadPaymentMethods(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods(e)),this._storeProjection.getState()})}submitOrder(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.submitOrder(e,t)),this._storeProjection.getState()})}submitPayment(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.submitPayment(e)),this._storeProjection.getState()})}finalizeOrder(e){return Gg(this,void 0,void 0,function*(){const{order:{getOrderOrThrow:t}}=this._store.getState();return yield this._store.dispatch(this._orderActionCreator.finalizeOrder(t().orderId,e)),this._storeProjection.getState()})}updateBillingAddress(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(e)),this._storeProjection.getState()})}updateShippingAddress(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.updateAddress(e)),this._storeProjection.getState()})}selectShippingOption(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t)),this._storeProjection.getState()})}signInCustomer(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signInCustomer(e,t)),this._storeProjection.getState()})}signOutCustomer(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signOutCustomer(e)),this._storeProjection.getState()})}createBuyNowCart(e,t){return Gg(this,void 0,void 0,function*(){const{body:n}=yield this._cartRequestSender.createBuyNowCart(e,t);return n})}applyStoreCredit(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(e,t)),this._storeProjection.getState()})}applyCoupon(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.applyCoupon(e,t)),this._storeProjection.getState()})}removeCoupon(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.removeCoupon(e,t)),this._storeProjection.getState()})}verifyCheckoutSpamProtection(){return Gg(this,void 0,void 0,function*(){const{checkout:e}=this._store.getState(),{shouldExecuteSpamCheck:t}=e.getCheckoutOrThrow();return t&&(yield this._store.dispatch(this._spamProtectionActionCreator.verifyCheckoutSpamProtection())),this._storeProjection.getState()})}loadCurrentOrder(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder(e)),this._storeProjection.getState()})}updatePaymentProviderCustomer(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(e)),this._storeProjection.getState()})}loadShippingCountries(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._shippingCountryActionCreator.loadCountries(e)),this._storeProjection.getState()})}deleteConsignment(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.deleteConsignment(e,t)),this._storeProjection.getState()})}initializePayment(e,t,n){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(e,t,n)),this._storeProjection.getState()})}forgetCheckout(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.forgetCheckout(e,t)),this._storeProjection.getState()})}remoteCheckoutSignOut(e,t){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e,t)),this._storeProjection.getState()})}validateCheckout(e,t){return Gg(this,void 0,void 0,function*(){yield this._checkoutValidator.validate(e,t)})}handlePaymentHumanVerification(e,t){return Gg(this,void 0,void 0,function*(){return"string"==typeof e?this._paymentHumanVerificationHandler.handle(e,null!=t?t:""):this._paymentHumanVerificationHandler.handle(e)})}widgetInteraction(e){return Gg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentStrategyWidgetActionCreator.widgetInteraction(e),{queueId:"widgetInteraction"}),this._storeProjection.getState()})}}class Wg{constructor(e){this._transformSelectors=e}create(e){return yt(e,this._transformSelectors)}}function $g(e,t){const{config:{getHost:i,getLocale:r}}=e.getState();t||(t=n({host:i()}));const a=new Wg(qg),s=new rn(new tn(t),new Pt(new kt(t)),new an(new sn(t))),d=new ny(new tn(t)),c=new wy(e),l=new Vm(new Bm(t),new ny(new tn(t))),u=new dt(new ht(t),new Rg(new Fg(t))),h=new Pg(new Eg(t),new tn(t)),p=new Wm(new $m(t)),m=new Cy(new by(Gm(e)),l,new Gy,new cy(Sn(o()))),y=new cy(Sn(o())),g=new Jt(new Zt(t),s,new mn(Sn(o()),new In(t))),f=new zg(new xg(t)),v=new Mt(new jt(t)),_=Sn(o()),S=new In(t),I=new mn(_,S),w=new Sg(t),C=new Ig,b=new kg(new Dg(t,{locale:r()}),e),P=new Cg(new bg(t),s),O=new Qm;return new Hg(e,a,s,d,c,l,u,h,p,m,y,g,w,f,v,I,C,b,P,O)}!function(e){e.LoadInstrumentsRequested="LOAD_INSTRUMENTS_REQUESTED",e.LoadInstrumentsSucceeded="LOAD_INSTRUMENTS_SUCCEEDED",e.LoadInstrumentsFailed="LOAD_INSTRUMENTS_FAILED",e.DeleteInstrumentRequested="DELETE_INSTRUMENT_REQUESTED",e.DeleteInstrumentSucceeded="DELETE_INSTRUMENT_SUCCEEDED",e.DeleteInstrumentFailed="DELETE_INSTRUMENT_FAILED"}(Vg||(Vg={}));class Yg{constructor(e){this._instrumentRequestSender=e}loadInstruments(){return e=>m.create(t=>{t.next(l(Vg.LoadInstrumentsRequested));const n=this._getSessionContext(e),i=this._getCurrentAccessToken(e),r=this._getShippingAddress(e);return this._getValidAccessToken(i).then(e=>this._instrumentRequestSender.loadInstruments(Object.assign(Object.assign({},n),{authToken:e.vaultAccessToken}),r).then(({body:n})=>{t.next(l(Vg.LoadInstrumentsSucceeded,n,e)),t.complete()})).catch(e=>{t.error(h(Vg.LoadInstrumentsFailed,e))})})}deleteInstrument(e){return t=>m.create(n=>{n.next(l(Vg.DeleteInstrumentRequested,void 0,{instrumentId:e}));const i=this._getSessionContext(t),r=this._getCurrentAccessToken(t);return this._getValidAccessToken(r).then(t=>this._instrumentRequestSender.deleteInstrument(Object.assign(Object.assign({},i),{authToken:t.vaultAccessToken}),e).then(({body:i})=>{n.next(l(Vg.DeleteInstrumentSucceeded,i,Object.assign({instrumentId:e},t))),n.complete()})).catch(t=>{n.error(h(Vg.DeleteInstrumentFailed,t,{instrumentId:e}))})})}_isValidVaultAccessToken(e){if(!e||!e.vaultAccessToken)return!1;return function(e){const t=new Date(e.getTime());return t.setMinutes(e.getMinutes()+2),t}(new Date(e.vaultAccessExpiry)).valueOf()>Date.now()}_getCurrentAccessToken(e){const{instruments:t}=e.getState(),n=t.getInstrumentsMeta();if(n)return{vaultAccessToken:n.vaultAccessToken,vaultAccessExpiry:n.vaultAccessExpiry}}_getValidAccessToken(e){return e&&this._isValidVaultAccessToken(e)?Promise.resolve(e):this._instrumentRequestSender.getVaultAccessToken().then(({body:e})=>e)}_getShippingAddress(e){const t=e.getState(),n=t.shippingAddress.getShippingAddresses();return n.length>1?n:t.shippingAddress.getShippingAddress()}_getSessionContext(e){const t=e.getState(),n=t.config.getStoreConfig(),i=t.cart.getCart();if(!n)throw new ot(tt.MissingCheckoutConfig);if(!i)throw new ot(tt.MissingCart);const{customerId:r}=i,{storeId:o}=n.storeProfile,{code:a}=n.shopperCurrency.isTransactional?n.shopperCurrency:n.currency;return{customerId:r,storeId:o,currencyCode:a}}}var Kg,Jg,Zg=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n};class Qg{transformResponse(e){const t=this._transformResponse(e),{body:n}=t,i=Zg(t,["body"]);return Object.assign(Object.assign({},i),{body:{vaultedInstruments:this._transformVaultedInstruments(n.vaulted_instruments)}})}transformErrorResponse(e){return this._transformResponse(e)}transformVaultAccessResponse(e){return Object.assign(Object.assign({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}})}_transformVaultedInstruments(e=[]){return e.map(e=>this._isPayPalInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,externalId:e.external_id,trustedShippingAddress:e.trusted_shipping_address,method:"paypal",type:"account"}}(e):this._isBankInstrument(e)?function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,trustedShippingAddress:e.trusted_shipping_address,accountNumber:e.account_number,issuer:e.issuer,iban:e.iban,method:e.method,type:"bank"}}(e):function(e){return{bigpayToken:e.bigpay_token,defaultInstrument:e.default_instrument,provider:e.provider,iin:e.iin,last4:e.last_4,expiryMonth:e.expiry_month,expiryYear:e.expiry_year,brand:e.brand,trustedShippingAddress:e.trusted_shipping_address,untrustedShippingCardVerificationMode:e.untrusted_shipping_address_card_verification_mode,method:e.method,type:"card"}}(e))}_isPayPalInstrument(e){return"paypal"===e.method_type}_isBankInstrument(e){return"bank"===e.method_type}_transformResponse(e){const{data:t}=e,n=Zg(e,["data"]);return Object.assign(Object.assign({},n),{body:t})}}class Xg{constructor(e,t){this._client=e,this._requestSender=t,this._transformer=new Qg}getVaultAccessToken({timeout:e}={}){return this._requestSender.get("/internalapi/v1/checkout/payments/vault-access-token",{timeout:e}).then(e=>Object.assign(Object.assign({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}}))}loadInstruments(e,t){return t?this._loadInstrumentsWithAddress(e,t):this._loadInstruments(e)}deleteInstrument(e,t){const n=Object.assign(Object.assign({},e),{instrumentId:t});return new Promise((e,t)=>{this._client.deleteShopperInstrument(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}_loadInstruments(e){return new Promise((t,n)=>{this._client.loadInstruments(e,(e,i)=>e?n(this._transformer.transformErrorResponse(e)):t(this._transformer.transformResponse(i)))})}_loadInstrumentsWithAddress(e,t){const n=Object.assign(Object.assign({},e),{shippingAddress:Array.isArray(t)?t.map(e=>Py(e)):Py(t)});return new Promise((e,t)=>{this._client.loadInstrumentsWithAddress(n,(n,i)=>n?t(this._transformer.transformErrorResponse(n)):e(this._transformer.transformResponse(i)))})}}!function(e){e.LoadPickupOptionsRequested="LOAD_PICKUP_OPTIONS_REQUESTED",e.LoadPickupOptionsSucceeded="LOAD_PICKUP_OPTIONS_SUCCEEDED",e.LoadPickupOptionsFailed="LOAD_PICKUP_OPTIONS_FAILED"}(Kg||(Kg={}));class ef{constructor(e){this._pickupOptionRequestSender=e}loadPickupOptions(e){return t=>new m(n=>{const i=this._hydrateApiQuery(t,e);n.next(l(Kg.LoadPickupOptionsRequested)),this._pickupOptionRequestSender.fetchPickupOptions(i).then(t=>{n.next(l(Kg.LoadPickupOptionsSucceeded,t.body.results,e)),n.complete()}).catch(e=>{n.error(h(Kg.LoadPickupOptionsFailed,e))})})}_hydrateApiQuery(e,t){const n=e.getState(),i=n.cart.getCartOrThrow();if(!i)throw new ot(tt.MissingCart);const r=n.consignments.getConsignmentById(t.consignmentId);if(!r)throw new ot(tt.MissingConsignments);const o=r.lineItemIds,a=i.lineItems.physicalItems.filter(e=>H(o,e.id)).map(e=>({variantId:e.variantId,quantity:e.quantity}));return{searchArea:t.searchArea,items:a}}}class tf{constructor(e){this._requestSender=e}fetchPickupOptions(e){return this._requestSender.post("/api/storefront/pickup-options",{headers:Object.assign({Accept:lt.Json},et),body:e})}}!function(e){e.UpdateAddressFailed="SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED",e.UpdateAddressRequested="SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED",e.UpdateAddressSucceeded="SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED",e.SelectOptionFailed="SHIPPING_STRATEGY_SELECT_OPTION_FAILED",e.SelectOptionRequested="SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED",e.SelectOptionSucceeded="SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED",e.InitializeFailed="SHIPPING_STRATEGY_INITIALIZE_FAILED",e.InitializeRequested="SHIPPING_STRATEGY_INITIALIZE_REQUESTED",e.InitializeSucceeded="SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED",e.DeinitializeFailed="SHIPPING_STRATEGY_DEINITIALIZE_FAILED",e.DeinitializeRequested="SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED",e.DeinitializeSucceeded="SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED",e.WidgetInteractionStarted="SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED",e.WidgetInteractionFinished="SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED",e.WidgetInteractionFailed="SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED"}(Jg||(Jg={}));class nf{constructor(e){this._strategyRegistry=e}updateAddress(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Jg.UpdateAddressRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).updateAddress(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Jg.UpdateAddressSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Jg.UpdateAddressFailed,e,{methodId:o}))})})}selectOption(e,t){return n=>m.create(i=>{const r=n.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;i.next(l(Jg.SelectOptionRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).selectOption(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{i.next(l(Jg.SelectOptionSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Jg.SelectOptionFailed,e,{methodId:o}))})})}initialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId,a=Object.assign(Object.assign({},e),{methodId:o});if(o&&i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Jg.InitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).initialize(a).then(()=>{n.next(l(Jg.InitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Jg.InitializeFailed,e,{methodId:o}))})})}deinitialize(e){return t=>m.create(n=>{const i=t.getState(),r=i.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId;if(o&&!i.shippingStrategies.isInitialized(o))return n.complete();n.next(l(Jg.DeinitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).deinitialize(Object.assign(Object.assign({},e),{methodId:o})).then(()=>{n.next(l(Jg.DeinitializeSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Jg.DeinitializeFailed,e,{methodId:o}))})})}widgetInteraction(e,t){return m.create(n=>{const i={methodId:t&&t.methodId};n.next(l(Jg.WidgetInteractionStarted,void 0,i)),e().then(()=>{n.next(l(Jg.WidgetInteractionFinished,void 0,i)),n.complete()}).catch(e=>{n.error(h(Jg.WidgetInteractionFailed,e,i))})})}}var rf,of=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class af{constructor(e,t,n,i,r){this._store=e,this._consignmentActionCreator=t,this._paymentMethodActionCreator=n,this._amazonPayV2PaymentProcessor=i,this._shippingStrategyActionCreator=r}updateAddress(e,t){const n=this._store.getState().shippingAddress.getShippingAddress();if(!n)throw new ot(tt.MissingShippingAddress);const i=Object.assign(Object.assign({},n),{customFields:e.customFields});return this._store.dispatch(this._consignmentActionCreator.updateAddress(i,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return of(this,void 0,void 0,function*(){const{amazonpay:t,methodId:n}=e;if(!t||!n)throw new Vt('Unable to proceed because "options.amazonpay" argument is not provided.');const i=(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))).paymentMethods.getPaymentMethodOrThrow(n);yield this._amazonPayV2PaymentProcessor.initialize(i);const{paymentToken:r,region:o}=i.initializationData,a=t.editAddressButtonId;if(r&&a){const e=this._shouldShowLoadingSpinner(o);this._bindEditButton(a,r,"changeAddress",e)}return this._store.getState()})}deinitialize(){return of(this,void 0,void 0,function*(){return yield this._amazonPayV2PaymentProcessor.deinitialize(),Promise.resolve(this._store.getState())})}_bindEditButton(e,t,n,i){const r=document.getElementById(e);if(r&&r.parentNode){if(i){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>this._showLoadingSpinner())}this._amazonPayV2PaymentProcessor.bindButton(e,t,n)}}_showLoadingSpinner(){return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction(()=>new Promise(w)),{queueId:"widgetInteraction"})}_shouldShowLoadingSpinner(e){return"us"!==e}}!function(e){e.CVV="cvv",e.PAN="pan"}(rf||(rf={}));var sf=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class df{constructor(e,t,n,i,r,o){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._braintreeIntegrationService=o}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){var t;return sf(this,void 0,void 0,function*(){const{methodId:n,braintreefastlane:i,fastlane:r}=e||{},o=r||i,{onPayPalFastlaneAddressChange:a}=o||{};if(!n)throw new Vt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState();if(!s.customer.getCustomerOrThrow().isGuest)return Promise.resolve(this._store.getState());try{if(this._shouldRunAuthenticationFlow()){const e=s.paymentMethods.getPaymentMethod(n),{clientToken:i,isFastlaneStylingEnabled:r}=(null==e?void 0:e.initializationData)||{};i||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n)));const a=Ao(r?null===(t=null==e?void 0:e.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,null==o?void 0:o.styles);yield this._runAuthenticationFlowOrThrow(n,a)}"function"==typeof a&&(yield this._shouldUseBraintreeFastlaneShippingComponent(n))&&a(()=>this._handleBraintreeFastlaneShippingAddressChange())}catch(e){}return Promise.resolve(this._store.getState())})}_shouldRunAuthenticationFlow(){var e;const t=this._store.getState(),n=null===(e=t.cart.getCart())||void 0===e?void 0:e.id,i=Fr.get("bc-fastlane-sessionId")||"",r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=Nl(r)?r:{};return(null==o?void 0:o.authenticationState)!==Mi.CANCELED&&!(null==o?void 0:o.authenticationState)&&i===n}_runAuthenticationFlowOrThrow(e,t){var n,i;return sf(this,void 0,void 0,function*(){const r=this._store.getState(),o=r.cart.getCartOrThrow(),a=r.countries.getCountries()||[],s=r.paymentMethods.getPaymentMethodOrThrow(e),{clientToken:d,config:c}=s;if(!d)throw new ot(tt.MissingPaymentMethod);this._braintreeIntegrationService.initialize(d);const l=yield this._braintreeIntegrationService.getBraintreeFastlane(null==o?void 0:o.id,null==c?void 0:c.testMode,t),u=(null===(n=r.customer.getCustomer())||void 0===n?void 0:n.email)||(null===(i=r.billingAddress.getBillingAddress())||void 0===i?void 0:i.email);if(!u)return;const{lookupCustomerByEmail:h,triggerAuthenticationFlow:p}=l.identity,{customerContextId:m}=yield h(u);if(!m)return;const{authenticationState:y,profileData:g}=yield p(m);if(y===Mi.CANCELED)return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:[],instruments:[]})),void Fr.remove("bc-fastlane-sessionId");const f=this._getPayPalBillingAddress(g),v=g.shippingAddress,_=g.shippingAddress.phoneNumber,S=this._mapPayPalToBcAddress(v,a,_),I=this._mapPayPalToBcAddress(f,a,_);if(I&&S){const t=this._mergeShippingAndBillingAddresses(S,I),n=this._mapPayPalToBcInstrument(e,g.card),i=n?[n]:[];yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:t,instruments:i})),I&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},I),{id:String(I.id)})))),S&&o.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(S)))}})}_getPayPalBillingAddress(e){const{name:t,card:n}=e,i=n.paymentSource.card.billingAddress;return Object.assign(Object.assign({},i),{firstName:i.firstName||(null==t?void 0:t.firstName),lastName:i.lastName||(null==t?void 0:t.lastName)})}_getCountryNameByCountryCode(e,t){const n=t.find(t=>t.code===e);return(null==n?void 0:n.name)||""}_mapPayPalToBcAddress(e,t,n,i){return{id:Number(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:this._getCountryNameByCountryCode(e.countryCodeAlpha2,t),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:n||"",customFields:i||[]}}_normalizeAddress(e){return le(e,["id"])}_mergeShippingAndBillingAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))?[e]:[e,t]}_mapPayPalToBcInstrument(e,t){if(!t)return;const{id:n,paymentSource:i}=t,{brand:r,expiry:o,lastDigits:a}=i.card,[s,d]=o.split("-");return{bigpayToken:n,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:rf.CVV,type:"card"}}_handleBraintreeFastlaneShippingAddressChange(){var e;return sf(this,void 0,void 0,function*(){const t=this._store.getState().countries.getCountries()||[],n=yield this._braintreeIntegrationService.getBraintreeFastlane(),{selectionChanged:i,selectedAddress:r}=yield n.profile.showShippingAddressSelector();if(i){const n=this._store.getState(),i=n.shippingAddress.getShippingAddressesOrThrow(),o=n.paymentProviderCustomer.getPaymentProviderCustomer(),a=Nl(o)?o:{},s=this._mapPayPalToBcAddress(r,t,r.phoneNumber,null===(e=i[0])||void 0===e?void 0:e.customFields);if(s){const e=this._filterAddresses([s,...a.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},a),{addresses:e}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(s)),s}}})}_filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this._isEqualAddresses(e,t))?e:[...e,t]:e,[])}_isEqualAddresses(e,t){return Y(this._normalizeAddress(e),this._normalizeAddress(t))}_shouldUseBraintreeFastlaneShippingComponent(e){var t;return sf(this,void 0,void 0,function*(){const n=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomer(),i=Nl(n)?n:{};if(i&&i!==Mi.CANCELED){const n=yield this._getBraintreePaymentMethodOrThrow(e);return!!(null===(t=null==n?void 0:n.initializationData)||void 0===t?void 0:t.isFastlaneEnabled)}return!1})}_getBraintreePaymentMethodOrThrow(e){return sf(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}}class cf{constructor(e,t){this._store=e,this._consignmentActionCreator=t}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(){return Promise.resolve(this._store.getState())}deinitialize(){return Promise.resolve(this._store.getState())}}var lf=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{d(i.next(e))}catch(e){o(e)}}function s(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}d((i=i.apply(e,t||[])).next())})};class uf{constructor(e,t,n,i,r,o,a){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i,this._paymentProviderCustomerActionCreator=r,this._paypalSdkScriptLoader=o,this._paypalCommerceFastlaneUtils=a}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}deinitialize(){return Promise.resolve(this._store.getState())}initialize(e){return lf(this,void 0,void 0,function*(){const{methodId:t,paypalcommercefastlane:n,fastlane:i}=e||{},r=i||n,{onPayPalFastlaneAddressChange:o,styles:a}=r||{};if(!t)throw new Vt('Unable to proceed because "methodId" argument is not provided.');const s=this._store.getState().customer.getCustomerOrThrow();if(!(null==s?void 0:s.isGuest))return Promise.resolve(this._store.getState());try{this._shouldAuthenticateUserWithFastlane()&&(yield this._initializePayPalSdk(t,a),yield this._authenticateUserWithFastlaneOtp(t)),"function"==typeof o&&this._shouldUsePayPalFastlaneShippingComponent()&&(yield this._initializePayPalSdk(t,a),o(()=>this._handlePayPalShippingAddressChange()))}catch(e){}return Promise.resolve(this._store.getState())})}_getPayPalPaymentMethodOrThrow(e){return lf(this,void 0,void 0,function*(){const t=this._store.getState().paymentMethods.getPaymentMethod(e);return t||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))).paymentMethods.getPaymentMethodOrThrow(e)})}_getPayPalCustomerAuthenticationState(){const e=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomerOrThrow();var t;return((t=e)&&("authenticationState"in t||"addresses"in t||"instruments"in t)?e:{}).authenticationState}_shouldAuthenticateUserWithFastlane(){const e=this._store.getState().cart.getCartOrThrow(),t=this._paypalCommerceFastlaneUtils.getStorageSessionId();return!this._getPayPalCustomerAuthenticationState()&&t===e.id}_shouldUsePayPalFastlaneShippingComponent(){const e=this._getPayPalCustomerAuthenticationState();return!!e&&e!==vs.CANCELED}_initializePayPalSdk(e,t){var n;return lf(this,void 0,void 0,function*(){const i=this._store.getState().cart.getCartOrThrow(),r=yield this._getPayPalPaymentMethodOrThrow(e),{isDeveloperModeApplicable:o,isFastlaneStylingEnabled:a}=(null==r?void 0:r.initializationData)||{},s=!!o,d=rd(a?null===(n=null==r?void 0:r.initializationData)||void 0===n?void 0:n.fastlaneStyles:{},t),c=yield this._paypalSdkScriptLoader.getPayPalFastlaneSdk(r,i.currency.code,i.id,i.locale);yield this._paypalCommerceFastlaneUtils.initializePayPalFastlane(c,s,d)})}_authenticateUserWithFastlaneOtp(e){var t,n;return lf(this,void 0,void 0,function*(){const i=this._store.getState(),r=i.cart.getCartOrThrow(),o=null===(t=i.customer.getCustomer())||void 0===t?void 0:t.email,a=null===(n=i.billingAddress.getBillingAddress())||void 0===n?void 0:n.email,s=o||a||"",{customerContextId:d}=yield this._paypalCommerceFastlaneUtils.lookupCustomerOrThrow(s),c=yield this._paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(d),{authenticationState:l,addresses:u,billingAddress:h,shippingAddress:p,instruments:m}=this._paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(e,c);yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:l,addresses:u,instruments:m})),c.authenticationState===vs.CANCELED?this._paypalCommerceFastlaneUtils.removeStorageSessionId():this._paypalCommerceFastlaneUtils.updateStorageSessionId(r.id),h&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},h),{id:String(h.id)})))),p&&r.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(p)))})}_handlePayPalShippingAddressChange(){var e;return lf(this,void 0,void 0,function*(){const t=this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:n,selectedAddress:i}=yield t.profile.showShippingAddressSelector();if(n){const t=this._store.getState(),n=t.shippingAddress.getShippingAddressesOrThrow(),r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=fp(r)?r:{},a=this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(i.address,i.name,i.phoneNumber,null===(e=n[0])||void 0===e?void 0:e.customFields),s=this._paypalCommerceFastlaneUtils.filterAddresses([a,...o.addresses||[]]);return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(Object.assign(Object.assign({},o),{addresses:s}))),yield this._store.dispatch(this._consignmentActionCreator.updateAddress(a)),a}})}}var hf;class pf{constructor(e,t,n,i){this._store=e,this._stripeScriptLoader=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=i}updateAddress(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return t=this,n=void 0,r=function*(){if(!e.stripeupe)throw new Vt('Unable to proceed because "options" argument is not provided.');const{container:t,gatewayId:n,methodId:i,onChangeShipping:r,getStyles:o,availableCountries:a,getStripeState:s}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new Vt(`Unable to proceed because "${e}" argument is not provided.`)});const d=yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n,{params:{method:i}})),c=d.paymentMethods.getPaymentMethodOrThrow(i,n),{initializationData:l}=c;if(!c||!c.initializationData.stripePublishableKey||!c.clientToken)throw new ot(tt.MissingPaymentMethod);let u;this._stripeUPEClient=yield this._stripeScriptLoader.getStripeClient(l,d.cart.getLocale(),ka.V3,Fa,La);const h=o&&o(),{form:{getShippingAddressFields:p},shippingAddress:{getShippingAddress:m}}=this._store.getState(),y=p([],"");u=h?{variables:{colorPrimary:h.fieldInnerShadow,colorBackground:h.fieldBackground,colorText:h.labelText,colorDanger:h.fieldErrorText,colorTextSecondary:h.labelText,colorTextPlaceholder:h.fieldPlaceholderText,spacingUnit:"4px",borderRadius:"4px"},rules:{".Input":{borderColor:h.fieldBorder,color:h.fieldText,boxShadow:h.fieldInnerShadow}}}:{variables:{spacingUnit:"4px",borderRadius:"4px"}},this._stripeElements=yield this._stripeScriptLoader.getElements(this._stripeUPEClient,{clientSecret:c.clientToken,appearance:u});const g=m(),f=y.find(e=>"phone"===e.name);let v={mode:Ca.SHIPPING,allowedCountries:[a],fields:{phone:"always"},validation:{phone:{required:f&&f.required?"always":"never"}},display:{name:ba.SPLIT}};if(g){const{stateOrProvinceCode:e,countryCode:t,lastName:n,firstName:i,phone:r,address1:o,address2:a,city:d,postalCode:c}=g,l=e&&t?s(t,e):e;v=Object.assign(Object.assign({},v),{defaultValues:{firstName:i,lastName:n,phone:r,address:{line1:o,line2:a,city:d,state:l,postal_code:c,country:t}}})}let _=this._stripeElements.getElement(Da.SHIPPING);return _&&_.destroy(),_=this._stripeElements.create(Da.SHIPPING,v),_.on(za.CHANGE,e=>{if(!("isNewAddress"in e))throw new ot(tt.MissingShippingAddress);(e.complete||e.isNewAddress)&&(this.sendData&&clearTimeout(this.sendData),this.sendData=setTimeout(()=>{r(Object.assign(Object.assign({},e),{phoneFieldRequired:!!f&&f.required}))},1e3))}),_.mount(`#${t}`),Promise.resolve(this._store.getState())},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}deinitialize(){return Promise.resolve(this._store.getState())}}!function(e){e.SendSignInEmailRequested="SEND_SIGNIN_EMAIL_REQUESTED",e.SendSignInEmailSucceeded="SEND_SIGNIN_EMAIL_SUCCEEDED",e.SendSignInEmailFailed="SEND_SIGNIN_EMAIL_FAILED"}(hf||(hf={}));class mf{constructor(e){this._requestSender=e}sendSignInEmail(e,t){return g(C(l(hf.SendSignInEmailRequested)),f(()=>{return n=this,i=void 0,o=function*(){const{body:n}=yield this._requestSender.sendSignInEmail(e,t);return l(hf.SendSignInEmailSucceeded,n)},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o})).pipe(P(e=>Ke(hf.SendSignInEmailFailed,e)))}}class yf{constructor(e){this._requestSender=e}sendSignInEmail({email:e,redirectUrl:t},{timeout:n}={}){const i=Object.assign({Accept:lt.JsonV1},et);return this._requestSender.post("/login.php?action=passwordless_login",{body:{email:e,redirect_url:t||Cn(window.top?window.top.location.href:"").pathname},headers:i,timeout:n})}}class gf{constructor(e){this._messageCustomizer=e}transform(e){var t;return e.message=(t=this._messageCustomizer(e))?t.split(/(?:\r\n|\n|\r)/).map(e=>e.replace(/^\s+/gm,"")).join(" ").trim():"",e}}let ff=class{constructor(e,t,n,i,r,o,a,s,d,c,l,u,h,p,m,y,g,f,v,_,S,I,w,C,b,P,O,E,A){this._store=e,this._storeProjection=t,this._extensionMessenger=n,this._extensionEventBroadcaster=i,this._b2bTokenActionCreator=r,this._billingAddressActionCreator=o,this._checkoutActionCreator=a,this._configActionCreator=s,this._customerActionCreator=d,this._consignmentActionCreator=c,this._countryActionCreator=l,this._couponActionCreator=u,this._customerStrategyActionCreator=h,this._errorActionCreator=p,this._giftCertificateActionCreator=m,this._instrumentActionCreator=y,this._orderActionCreator=g,this._paymentMethodActionCreator=f,this._paymentStrategyActionCreator=v,this._pickupOptionActionCreator=_,this._shippingCountryActionCreator=S,this._shippingStrategyActionCreator=I,this._signInEmailActionCreator=w,this._spamProtectionActionCreator=C,this._storeCreditActionCreator=b,this._subscriptionsActionCreator=P,this._formFieldsActionCreator=O,this._extensionActionCreator=E,this._workerExtensionMessenger=A,this._errorTransformer=function(e="development"===vt()){return new gf(t=>{if(!e||!function(e){return!(!e.subtype&&!e.type)}(t))return t.message;switch(t.subtype||t.type){case tt.MissingConsignments:return`\n ${t.message}\n The data could be unavailable because no shipping address has been provided.\n To fix this, create a consignment or update the shipping address before performing\n the same action again.\n `;case tt.MissingCart:case tt.MissingCheckout:return`\n ${t.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you can try calling \`CheckoutService#loadCheckout\`\n before performing the same action again.\n `;case tt.MissingCheckoutConfig:return`\n ${t.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you need to make sure \`CheckoutService\` is initialized\n properly by calling \`CheckoutService#loadCheckout\` before performing any\n other actions.\n `;case tt.MissingOrder:return`\n ${t.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you can try calling \`CheckoutService#loadOrder\`\n before performing the same action again.\n `;case tt.MissingOrderId:return`\n ${t.message}\n The data could be unavailable because no order has been created yet. You have\n to first create the order before you can perform the action.\n `;case tt.MissingPaymentMethod:return`\n ${t.message}\n The data could be unavailable because it has not loaded from the server, or\n configured by the merchant yet. To fix the former issue, you can try calling\n \`CheckoutService#loadPaymentMethods\` before performing the same action again.\n `;case ln.CustomerNotInitialized:return"\n In order to initialize the customer step of checkout, you need to call\n `CheckoutService#initializeCustomer`. Afterwards, you should be able to\n submit customer details.\n ";case ln.PaymentNotInitialized:return`\n ${t.message}\n In order to initialize the payment step of checkout, you need to call\n \`CheckoutService#initializePayment\`. Afterwards, you should be able to\n submit payment details.\n `;case ln.ShippingNotInitialized:return`\n ${t.message}\n In order to initialize the shipping step of checkout, you need to call\n \`CheckoutService#initializeShipping\`. Afterwards, you should be able to\n submit shipping details.\n `;default:return t.message}})}()}getState(){return this._storeProjection.getState()}notifyState(){this._storeProjection.notifyState()}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}hydrateInitialState(e){return this._dispatch(this._checkoutActionCreator.hydrateInitialState(e))}loadCheckout(e,t){return this._dispatch(e?this._checkoutActionCreator.loadCheckout(e,t):this._checkoutActionCreator.loadDefaultCheckout(t))}updateCheckout(e,t){const n=this._checkoutActionCreator.updateCheckout(e,t);return this._dispatch(n)}loadOrder(e,t){const n=this._orderActionCreator.loadOrder(e,t),i=this._formFieldsActionCreator.loadFormFields(t),r=this._configActionCreator.loadConfig(t);return Promise.all([this._dispatch(n),this._dispatch(r,{queueId:"config"}),this._dispatch(i,{queueId:"formFields"})]).then(()=>this.getState())}submitOrder(e,t){const n=this._paymentStrategyActionCreator.execute(e,t);return this._dispatch(n,{queueId:"paymentStrategy"})}finalizeOrderIfNeeded(e){const t=this._paymentStrategyActionCreator.finalize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadPaymentMethods(e){const t=this._paymentMethodActionCreator.loadPaymentMethods(e);return this._dispatch(t,{queueId:"paymentMethods"})}loadPaymentMethodByIds(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethodsById(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}loadPaymentMethod(e,t){const n=this._paymentMethodActionCreator.loadPaymentMethod(e,t);return this._dispatch(n,{queueId:"paymentMethods"})}initializePayment(e){const t=this._paymentStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}deinitializePayment(e){const t=this._paymentStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"paymentStrategy"})}loadBillingCountries(e){const t=this._countryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"billingCountries"})}loadShippingCountries(e){const t=this._shippingCountryActionCreator.loadCountries(e);return this._dispatch(t,{queueId:"shippingCountries"})}loadPickupOptions(e){const t=this._pickupOptionActionCreator.loadPickupOptions(e);return this._dispatch(t,{queueId:"pickupOptions"})}loadBillingAddressFields(e){return this.loadBillingCountries(e)}loadShippingAddressFields(e){return this.loadShippingCountries(e)}initializeCustomer(e){const t=this._customerStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}deinitializeCustomer(e){const t=this._customerStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"customerStrategy"})}sendSignInEmail(e,t){const n=this._signInEmailActionCreator.sendSignInEmail(e,t);return this._dispatch(n,{queueId:"signInEmail"})}getB2BToken(e){const t=this._b2bTokenActionCreator.loadB2BToken(e);return this._dispatch(t,{queueId:"b2bToken"})}createCustomerAccount(e,t){const n=this._customerActionCreator.createCustomer(e,t);return this._dispatch(n)}createCustomerAddress(e,t){const n=this._customerActionCreator.createAddress(e,t);return this._dispatch(n)}updateSubscriptions(e,t){const n=this._subscriptionsActionCreator.updateSubscriptions(e,t);return this._dispatch(n,{queueId:"subscriptions"})}continueAsGuest(e,t){const n=this._billingAddressActionCreator.continueAsGuest(e,t);return this._dispatch(n)}signInCustomer(e,t){const n=this._customerStrategyActionCreator.signIn(e,t);return this._dispatch(n,{queueId:"customerStrategy"})}signOutCustomer(e){const t=this._customerStrategyActionCreator.signOut(e);return this._dispatch(t,{queueId:"customerStrategy"})}executePaymentMethodCheckout(e){const t=this._customerStrategyActionCreator.executePaymentMethodCheckout(e);return this._dispatch(t,{queueId:"customerStrategy"})}loadShippingOptions(e){const t=this._consignmentActionCreator.loadShippingOptions(e);return this._dispatch(t)}initializeShipping(e){const t=this._shippingStrategyActionCreator.initialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}deinitializeShipping(e){const t=this._shippingStrategyActionCreator.deinitialize(e);return this._dispatch(t,{queueId:"shippingStrategy"})}selectShippingOption(e,t){const n=this._shippingStrategyActionCreator.selectOption(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateShippingAddress(e,t){const n=this._shippingStrategyActionCreator.updateAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}createConsignments(e,t){const n=this._consignmentActionCreator.createConsignments(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}deleteConsignment(e,t){const n=this._consignmentActionCreator.deleteConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}updateConsignment(e,t){const n=this._consignmentActionCreator.updateConsignment(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}assignItemsToAddress(e,t){const n=this._consignmentActionCreator.assignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}unassignItemsToAddress(e,t){const n=this._consignmentActionCreator.unassignItemsByAddress(e,t);return this._dispatch(n,{queueId:"shippingStrategy"})}selectConsignmentShippingOption(e,t,n){const i=this._consignmentActionCreator.updateShippingOption({id:e,shippingOptionId:t},n);return this._dispatch(i,{queueId:"shippingStrategy"})}updateBillingAddress(e,t={}){const n=this._billingAddressActionCreator.updateAddress(e,t);return this._dispatch(n)}applyStoreCredit(e,t){const n=this._storeCreditActionCreator.applyStoreCredit(e,t);return this._dispatch(n)}applyCoupon(e,t){const n=this._couponActionCreator.applyCoupon(e,t);return this._dispatch(n)}removeCoupon(e,t){const n=this._couponActionCreator.removeCoupon(e,t);return this._dispatch(n)}applyGiftCertificate(e,t){const n=this._giftCertificateActionCreator.applyGiftCertificate(e,t);return this._dispatch(n)}removeGiftCertificate(e,t){const n=this._giftCertificateActionCreator.removeGiftCertificate(e,t);return this._dispatch(n)}loadInstruments(){const e=this._instrumentActionCreator.loadInstruments();return this._dispatch(e)}deleteInstrument(e){const t=this._instrumentActionCreator.deleteInstrument(e);return this._dispatch(t).then(()=>this.loadInstruments())}clearError(e){const t=this._errorActionCreator.clearError(e);return this._dispatch(t)}initializeSpamProtection(e){const t=this._spamProtectionActionCreator.initialize(e);return this._dispatch(t,{queueId:"spamProtection"})}executeSpamCheck(){const e=this._spamProtectionActionCreator.verifyCheckoutSpamProtection();return this._dispatch(e,{queueId:"spamProtection"})}loadExtensions(e){const t=this._extensionActionCreator.loadExtensions(e);return this._dispatch(t,{queueId:"extensions"})}renderExtension(e,t){return n=this,i=void 0,o=function*(){const n=this._extensionActionCreator.renderExtension(e,t,this._workerExtensionMessenger),i=yield this._dispatch(n,{queueId:"extensions"});return this._extensionEventBroadcaster.listen(),i},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}clearExtensionCache(e){this._extensionMessenger.clearCacheByRegion(e)}postMessageToExtension(e,t){this._extensionMessenger.post(e,t)}handleExtensionCommand(e,t,n){return this._extensionMessenger.listenForCommand(e,t,n)}handleExtensionQuery(e,t,n){return this._extensionMessenger.listenForQuery(e,t,n)}_dispatch(e,t){return this._store.dispatch(e,t).then(()=>this.getState()).catch(e=>{throw this._errorTransformer.transform(e)})}};ff=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],ff);const vf=ff;function _f(e){return(...t)=>{const n=t.pop();return e(...t,(...e)=>{const t=n(...e);return"function"==typeof t?Pe(t):t})}}const Sf=_f(Re),If=_f(Fe(Le,(e,t)=>je(e,t)));class wf extends Et{constructor(e,t){super(e,{message:t||"An unexpected error has occurred. The checkout process cannot continue as a result."}),this.name="UnrecoverableError",this.type="unrecoverable"}}function Cf(e){return e.reduce((e,t)=>t?[...e,t]:e,[]).join(" ")}class bf extends Et{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}class Pf{constructor(){this._factoryMethods={},this.register("default",(e,t)=>new Et(e,{message:t})),this.register("internal",(e,t)=>function(e,t){const{body:n}=e,{errors:i=[]}=n;return new Et(e,{message:Cf(i)||n.detail||n.title||t,errors:i.length?i.map(e=>({code:n.type,message:e})):[{code:n.type,message:n.detail||n.title}]})}(e,t)),this.register("storefront",(e,t)=>function(e,t){const{body:n}=e;return new Et(e,{message:t||n.detail||n.title,errors:[{code:n.code||n.type,message:n.detail||n.title}]})}(e,t)),this.register("payment",(e,t)=>ly(e,t)),this.register("timeout",e=>new bf(e))}register(e,t){this._factoryMethods[e]=t}createError(e,t){return(this._factoryMethods[this._getType(e)]||this._factoryMethods.default)(e,t)}_getType(e){if(0===e.status)return"timeout";if(this._isStorefrontErrorResponseBody(e.body))return"storefront";if(this._isInternalErrorResponseBody(e.body)){const t=re(e.body.type.split("/"));return t&&this._factoryMethods[t]?t:"internal"}const t=re(e.body&&e.body.errors);return t&&t.code&&this._factoryMethods[t.code]?t.code:"payment"}_isStorefrontErrorResponseBody(e){const t=e;return!this._isInternalErrorResponseBody(e)&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status&&"string"==typeof t.detail}_isInternalErrorResponseBody(e){const t=e;return"object"==typeof t.errors&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status}}function Of(e,t){return Array.isArray(e)?e.map(e=>Of(e,t)):Q(e)?_e(ue(e,t),(e,n,i)=>{e[i]=Of(n,t)},{}):e}function Ef(e,t){return function(e){return e.type===mt.ClearError}(t)?Of(e,e=>e===t.payload):e}function Af(e,t,n){return e===t||(e&&t&&"object"==typeof e&&"object"==typeof t?Array.isArray(e)&&Array.isArray(t)?function(e,t,n){if(e.length!==t.length)return!1;for(let i=0,r=e.length;i<r;i++)if(!Af(e[i],t[i],n))return!1;return!0}(e,t,n):!Array.isArray(e)&&!Array.isArray(t)&&(e instanceof Date&&t instanceof Date?function(e,t){return e.getTime()===t.getTime()}(e,t):!(e instanceof Date||t instanceof Date)&&(e instanceof RegExp&&t instanceof RegExp?function(e,t){return e.toString()===t.toString()}(e,t):!(e instanceof RegExp||t instanceof RegExp)&&function(e,t,n){const i=n&&n.keyFilter,r=i?Object.keys(e).filter(i):Object.keys(e),o=i?Object.keys(t).filter(i):Object.keys(t);if(r.length!==o.length)return!1;for(let i=0,o=r.length;i<o;i++){const o=r[i];if(!Object.prototype.hasOwnProperty.call(t,o))return!1;if(!Af(e[o],t[o],n))return!1}return!0}(e,t,n))):e===t)}function Tf(e,t,n){return e&&Object.prototype.hasOwnProperty.call(e,t)&&Af(e[t],n)?e:Object.assign(Object.assign({},e),{[t]:n})}const kf={errors:{},statuses:{}};function Df(e=kf,t){return d({data:Mf,errors:c(zf,Ef),statuses:xf})(e,t)}function Mf(e,t){return t.type===Je.LoadB2BTokenSucceeded?t.payload:e}function zf(e=kf.errors,t){switch(t.type){case Je.LoadB2BTokenRequested:case Je.LoadB2BTokenSucceeded:return Tf(e,"loadError",void 0);case Je.LoadB2BTokenFailed:return Tf(e,"loadError",t.payload);default:return e}}function xf(e=kf.statuses,t){switch(t.type){case Je.LoadB2BTokenRequested:return Tf(e,"isLoading",!0);case Je.LoadB2BTokenFailed:case Je.LoadB2BTokenSucceeded:return Tf(e,"isLoading",!1);default:return e}}function Nf(e,t){return void 0===t||Af(e,t)?e:t}const Rf={errors:{},statuses:{}};function Ff(e=Rf,t){return d({data:Lf,errors:c(jf,Ef),statuses:Bf})(e,t)}function Lf(e,t){var n,i;switch(t.type){case nt.UpdateBillingAddressSucceeded:case nt.ContinueAsGuestSucceeded:case Yt.LoadCheckoutSucceeded:return Nf(e,t.payload&&t.payload.billingAddress);case Kt.HydrateInitialState:return Nf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.billingAddress);default:return e}}function jf(e=Rf.errors,t){switch(t.type){case Yt.LoadCheckoutRequested:case Yt.LoadCheckoutSucceeded:return Tf(e,"loadError",void 0);case Yt.LoadCheckoutFailed:return Tf(e,"loadError",t.payload);case nt.UpdateBillingAddressRequested:case nt.UpdateBillingAddressSucceeded:return Tf(e,"updateError",void 0);case nt.UpdateBillingAddressFailed:return Tf(e,"updateError",t.payload);case Mg.UpdateSubscriptionsRequested:case Mg.UpdateSubscriptionsSucceeded:case nt.ContinueAsGuestRequested:case nt.ContinueAsGuestSucceeded:return Tf(e,"continueAsGuestError",void 0);case Mg.UpdateSubscriptionsFailed:case nt.ContinueAsGuestFailed:return Tf(e,"continueAsGuestError",t.payload);default:return e}}function Bf(e=Rf.statuses,t){switch(t.type){case Yt.LoadCheckoutRequested:return Tf(e,"isLoading",!0);case Yt.LoadCheckoutSucceeded:case Yt.LoadCheckoutFailed:return Tf(e,"isLoading",!1);case nt.UpdateBillingAddressRequested:return Tf(e,"isUpdating",!0);case nt.UpdateBillingAddressFailed:case nt.UpdateBillingAddressSucceeded:return Tf(e,"isUpdating",!1);case nt.ContinueAsGuestRequested:case Mg.UpdateSubscriptionsRequested:return Tf(e,"isContinuingAsGuest",!0);case Mg.UpdateSubscriptionsSucceeded:case Mg.UpdateSubscriptionsFailed:case nt.ContinueAsGuestFailed:case nt.ContinueAsGuestSucceeded:return Tf(e,"isContinuingAsGuest",!1);default:return e}}const Uf=function e(t,n,i){const{matchObject:r=(e,t)=>void 0!==e.id&&e.id===t.id}=i||{};if(!t)return n;if(!n||t===n)return t;let o=0,a=0;const s=(e,t,n)=>(o+=e===t?1:0,a+=e===n?1:0,e),d=n.map((n,i)=>{const o=t&&t[i];return Lg(o)&&Lg(n)?r(o,n)?s(qf(o,n),o,n):s(Nf(o,n),o,n):W(o)&&W(n)?s(e(o,n),o,n):s(Nf(o,n),o,n)});return o===n.length&&t&&t.length===n.length?t:a===n.length?n:d},qf=function e(t,n){return t?n&&t!==n?Object.keys(n).reduce((t,i)=>{const r=t[i],o=n[i];return Lg(r)&&Lg(o)?Tf(t,i,e(r,o)):W(r)&&W(o)?Tf(t,i,Uf(r,o)):Tf(t,i,o)},t):t:n},Vf={errors:{},statuses:{}};function Gf(e=Vf,t){return d({data:Hf,errors:c($f,Ef),statuses:Wf})(e,t)}function Hf(e,t){var n,i;switch(t.type){case nt.UpdateBillingAddressSucceeded:case Yt.LoadCheckoutSucceeded:case wg.CreateConsignmentsSucceeded:case wg.DeleteConsignmentSucceeded:case wg.UpdateConsignmentSucceeded:case wg.UpdateShippingOptionSucceeded:case wg.LoadShippingOptionsSucceeded:case Dt.ApplyCouponSucceeded:case Dt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return qf(e,t.payload&&t.payload.cart);case Kt.HydrateInitialState:return qf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.cart);default:return e}}function Wf(e=Vf.statuses,t){switch(t.type){case Yt.LoadCheckoutRequested:return Tf(e,"isLoading",!0);case Yt.LoadCheckoutFailed:case Yt.LoadCheckoutSucceeded:return Tf(e,"isLoading",!1);default:return e}}function $f(e=Vf.errors,t){switch(t.type){case Yt.LoadCheckoutRequested:case Yt.LoadCheckoutSucceeded:return Tf(e,"loadError",void 0);case Yt.LoadCheckoutFailed:return Tf(e,"loadError",t.payload);default:return e}}var Yf;!function(e){e.InitializeButtonFailed="INITIALIZE_BUTTON_FAILED",e.InitializeButtonRequested="INITIALIZE_BUTTON_REQUESTED",e.InitializeButtonSucceeded="INITIALIZE_BUTTON_SUCCEEDED",e.DeinitializeButtonFailed="DEINITIALIZE_BUTTON_FAILED",e.DeinitializeButtonRequested="DEINITIALIZE_BUTTON_REQUESTED",e.DeinitializeButtonSucceeded="DEINITIALIZE_BUTTON_SUCCEEDED"}(Yf||(Yf={}));const Kf={data:{},errors:{},statuses:{}},Jf={initializedContainers:{}},Zf={},Qf={};function Xf(e=Kf,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:ev}),errors:d({[t.meta.methodId]:tv}),statuses:d({[t.meta.methodId]:nv})})(e,t):e}function ev(e=Jf,t){switch(t.type){case Yf.InitializeButtonSucceeded:return t.meta&&t.meta.containerId?qf(e,{initializedContainers:{[t.meta.containerId]:!0}}):e;case Yf.DeinitializeButtonSucceeded:return Tf(e,"initializedContainers",{})}return e}function tv(e=Zf,t){switch(t.type){case Yf.InitializeButtonRequested:case Yf.InitializeButtonSucceeded:return Tf(e,"initializeError",void 0);case Yf.InitializeButtonFailed:return Tf(e,"initializeError",t.payload);case Yf.DeinitializeButtonRequested:case Yf.DeinitializeButtonSucceeded:return Tf(e,"deinitializeError",void 0);case Yf.DeinitializeButtonFailed:return Tf(e,"deinitializeError",t.payload);default:return e}}function nv(e=Qf,t){switch(t.type){case Yf.InitializeButtonRequested:return Tf(e,"isInitializing",!0);case Yf.InitializeButtonFailed:case Yf.InitializeButtonSucceeded:return Tf(e,"isInitializing",!1);case Yf.DeinitializeButtonRequested:return Tf(e,"isDeinitializing",!0);case Yf.DeinitializeButtonFailed:case Yf.DeinitializeButtonSucceeded:return Tf(e,"isDeinitializing",!1);default:return e}}const iv={meta:{},errors:{},statuses:{}};function rv(e=iv,t){return d({data:ov,errors:c(av,Ef),statuses:sv})(e,t)}function ov(e,t){var n;switch(t.type){case bt.LoadConfigSucceeded:return qf(e,t.payload);case Kt.HydrateInitialState:return qf(e,null===(n=t.payload)||void 0===n?void 0:n.config);default:return e}}function av(e=iv.errors,t){switch(t.type){case bt.LoadConfigSucceeded:return Tf(e,"loadError",void 0);case bt.LoadConfigFailed:return Tf(e,"loadError",t.payload);default:return e}}function sv(e=iv.statuses,t){switch(t.type){case bt.LoadConfigRequested:return Tf(e,"isLoading",!0);case bt.LoadConfigSucceeded:case bt.LoadConfigFailed:return Tf(e,"isLoading",!1);default:return e}}const dv={errors:{},statuses:{}};function cv(e=dv,t){return d({data:lv,errors:c(uv,Ef),statuses:hv})(e,t)}function lv(e,t){var n,i;switch(t.type){case Yt.LoadCheckoutSucceeded:case Dt.ApplyCouponSucceeded:case wg.UpdateShippingOptionSucceeded:case Dt.RemoveCouponSucceeded:case Mm.LoadOrderSucceeded:return Uf(e,t.payload&&t.payload.coupons);case Kt.HydrateInitialState:return Uf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.coupons);default:return e}}function uv(e={},t){switch(t.type){case Dt.ApplyCouponRequested:case Dt.ApplyCouponSucceeded:return Tf(e,"applyCouponError",void 0);case Dt.ApplyCouponFailed:return Tf(e,"applyCouponError",t.payload);case Dt.RemoveCouponRequested:case Dt.RemoveCouponSucceeded:return Tf(e,"removeCouponError",void 0);case Dt.RemoveCouponFailed:return Tf(e,"removeCouponError",t.payload);default:return e}}function hv(e={},t){switch(t.type){case Dt.ApplyCouponRequested:return Tf(e,"isApplyingCoupon",!0);case Dt.ApplyCouponSucceeded:case Dt.ApplyCouponFailed:return Tf(e,"isApplyingCoupon",!1);case Dt.RemoveCouponRequested:return Tf(e,"isRemovingCoupon",!0);case Dt.RemoveCouponSucceeded:case Dt.RemoveCouponFailed:return Tf(e,"isRemovingCoupon",!1);default:return e}}const pv={errors:{},statuses:{}};function mv(e=pv,t){return d({data:yv,errors:c(gv,Ef),statuses:fv})(e,t)}function yv(e,t){var n,i;switch(t.type){case Yt.LoadCheckoutSucceeded:case wg.CreateConsignmentsSucceeded:case wg.UpdateConsignmentSucceeded:case wg.DeleteConsignmentSucceeded:case wg.UpdateShippingOptionSucceeded:case Dt.ApplyCouponSucceeded:case Dt.RemoveCouponSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:return Uf(e,t.payload&&t.payload.giftCertificates);case Kt.HydrateInitialState:return Uf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.giftCertificates);default:return e}}function gv(e=pv.errors,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:case Nt.ApplyGiftCertificateSucceeded:return Tf(e,"applyGiftCertificateError",void 0);case Nt.ApplyGiftCertificateFailed:return Tf(e,"applyGiftCertificateError",t.payload);case Nt.RemoveGiftCertificateRequested:case Nt.RemoveGiftCertificateSucceeded:return Tf(e,"removeGiftCertificateError",void 0);case Nt.RemoveGiftCertificateFailed:return Tf(e,"removeGiftCertificateError",t.payload);default:return e}}function fv(e=pv.statuses,t){switch(t.type){case Nt.ApplyGiftCertificateRequested:return Tf(e,"isApplyingGiftCertificate",!0);case Nt.ApplyGiftCertificateSucceeded:case Nt.ApplyGiftCertificateFailed:return Tf(e,"isApplyingGiftCertificate",!1);case Nt.RemoveGiftCertificateRequested:return Tf(e,"isRemovingGiftCertificate",!0);case Nt.RemoveGiftCertificateSucceeded:case Nt.RemoveGiftCertificateFailed:return Tf(e,"isRemovingGiftCertificate",!1);default:return e}}const vv={errors:{},statuses:{}};function _v(e=vv,t){return d({data:Sv,errors:c(Iv,Ef),statuses:wv})(e,t)}function Sv(e,t){var n,i;switch(t.type){case nt.ContinueAsGuestSucceeded:case Yt.LoadCheckoutSucceeded:return qf(e,t.payload&&t.payload.customer);case Ft.CreateCustomerAddressSucceeded:return qf(e,t.payload);case Kt.HydrateInitialState:return qf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.customer);default:return e}}function Iv(e=vv.errors,t){switch(t.type){case Ft.CreateCustomerRequested:case Ft.CreateCustomerSucceeded:return Tf(e,"createError",void 0);case Ft.CreateCustomerFailed:return Tf(e,"createError",t.payload);case Ft.CreateCustomerAddressRequested:case Ft.CreateCustomerAddressSucceeded:return Tf(e,"createAddressError",void 0);case Ft.CreateCustomerAddressFailed:return Tf(e,"createAddressError",t.payload);default:return e}}function wv(e=vv.statuses,t){switch(t.type){case Ft.CreateCustomerRequested:return Tf(e,"isCreating",!0);case Ft.CreateCustomerFailed:case Ft.CreateCustomerSucceeded:return Tf(e,"isCreating",!1);case Ft.CreateCustomerAddressRequested:return Tf(e,"isCreatingAddress",!0);case Ft.CreateCustomerAddressFailed:case Ft.CreateCustomerAddressSucceeded:return Tf(e,"isCreatingAddress",!1);default:return e}}const Cv={data:{},errors:{},statuses:{}};function bv(e=Cv,t){return d({data:Pv,errors:c(Ov,Ef),statuses:Ev})(e,t)}function Pv(e=Cv.data,t){switch(t.type){case $t.InitializeSucceeded:return qf(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case $t.DeinitializeSucceeded:return qf(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function Ov(e=Cv.errors,t){switch(t.type){case $t.InitializeRequested:case $t.InitializeSucceeded:return qf(e,{initializeErrors:Object.assign({},e.initializeErrors),initializeMethodId:e.initializeMethodId?e.initializeMethodId:void 0});case $t.InitializeFailed:return qf(e,{initializeErrors:Object.assign(Object.assign({},e.initializeErrors),{[t.meta&&t.meta.methodId]:t.payload}),initializeMethodId:t.meta&&t.meta.methodId});case $t.DeinitializeRequested:case $t.DeinitializeSucceeded:return qf(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case $t.DeinitializeFailed:return qf(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case $t.SignInRequested:case $t.SignInSucceeded:return qf(e,{signInError:void 0,signInMethodId:void 0});case $t.SignInFailed:return qf(e,{signInError:t.payload,signInMethodId:t.meta&&t.meta.methodId});case $t.SignOutRequested:case $t.SignOutSucceeded:return qf(e,{signOutError:void 0,signOutMethodId:void 0});case $t.SignOutFailed:return qf(e,{signOutError:t.payload,signOutMethodId:t.meta&&t.meta.methodId});case $t.ExecutePaymentMethodCheckoutRequested:case $t.ExecutePaymentMethodCheckoutSucceeded:return qf(e,{executePaymentMethodCheckoutError:void 0,executePaymentMethodCheckoutMethodId:void 0});case $t.ExecutePaymentMethodCheckoutFailed:return qf(e,{executePaymentMethodCheckoutError:t.payload,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case $t.WidgetInteractionStarted:case $t.WidgetInteractionFinished:return qf(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case $t.WidgetInteractionFailed:return qf(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function Ev(e=Cv.statuses,t){switch(t.type){case $t.InitializeRequested:return qf(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case $t.InitializeFailed:case $t.InitializeSucceeded:return qf(e,{isInitializing:!1,initializeMethodId:void 0});case $t.DeinitializeRequested:return qf(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case $t.DeinitializeFailed:case $t.DeinitializeSucceeded:return qf(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case $t.SignInRequested:return qf(e,{isSigningIn:!0,signInMethodId:t.meta&&t.meta.methodId});case $t.SignInFailed:case $t.SignInSucceeded:return qf(e,{isSigningIn:!1,signInMethodId:void 0});case $t.SignOutRequested:return qf(e,{isSigningOut:!0,signOutMethodId:t.meta&&t.meta.methodId});case $t.SignOutFailed:case $t.SignOutSucceeded:return qf(e,{isSigningOut:!1,signOutMethodId:void 0});case $t.ExecutePaymentMethodCheckoutRequested:return qf(e,{isExecutingPaymentMethodCheckout:!0,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case $t.ExecutePaymentMethodCheckoutFailed:case $t.ExecutePaymentMethodCheckoutSucceeded:return qf(e,{isExecutingPaymentMethodCheckout:!1,executePaymentMethodCheckoutMethodId:void 0});case $t.WidgetInteractionStarted:return qf(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case $t.WidgetInteractionFinished:case $t.WidgetInteractionFailed:return qf(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const Av={errors:{},statuses:{}};function Tv(e=Av,t){return d({data:kv,errors:c(Dv,Ef),statuses:Mv})(e,t)}function kv(e,t){var n;return t.type===un.LoadExtensionsSucceeded?Uf(e,t.payload):t.type===Kt.HydrateInitialState?Uf(e,null===(n=t.payload)||void 0===n?void 0:n.extensions):e}function Dv(e=Av.errors,t){switch(t.type){case un.LoadExtensionsRequested:case un.LoadExtensionsSucceeded:return Tf(e,"loadError",void 0);case un.RenderExtensionRequested:case un.RenderExtensionSucceeded:return Tf(e,"renderError",void 0);case un.LoadExtensionsFailed:return Tf(e,"loadError",t.payload);case un.RenderExtensionFailed:return Tf(e,"renderError",t.payload);default:return e}}function Mv(e=Av.statuses,t){switch(t.type){case un.LoadExtensionsRequested:return Tf(e,"isLoading",!0);case un.LoadExtensionsSucceeded:case un.LoadExtensionsFailed:return Tf(e,"isLoading",!1);default:return e}}const zv={errors:{},statuses:{}};function xv(e=zv,t){return d({data:Nv,extraFields:Rv,errors:c(Fv,Ef),statuses:Lv})(e,t)}function Nv(e,t){var n;switch(t.type){case nn.LoadFormFieldsSucceeded:return qf(e,t.payload);case Kt.HydrateInitialState:return qf(e,null===(n=t.payload)||void 0===n?void 0:n.formFields);default:return e}}function Rv(e,t){var n,i;return t.type===Kt.HydrateInitialState&&null!==(i=null===(n=t.payload)||void 0===n?void 0:n.extraFields)&&void 0!==i?i:e}function Fv(e=zv.errors,t){switch(t.type){case nn.LoadFormFieldsSucceeded:return Tf(e,"loadError",void 0);case nn.LoadFormFieldsFailed:return Tf(e,"loadError",t.payload);default:return e}}function Lv(e=zv.statuses,t){switch(t.type){case nn.LoadFormFieldsRequested:return Tf(e,"isLoading",!0);case nn.LoadFormFieldsSucceeded:case nn.LoadFormFieldsFailed:return Tf(e,"isLoading",!1);default:return e}}const jv={errors:{},statuses:{}};function Bv(e=jv,t){return d({data:Uv,errors:c(qv,Ef),statuses:Vv})(e,t)}function Uv(e,t){return t.type===Dm.LoadCountriesSucceeded?Uf(e,t.payload):e}function qv(e=jv.errors,t){switch(t.type){case Dm.LoadCountriesRequested:case Dm.LoadCountriesSucceeded:return Tf(e,"loadError",void 0);case Dm.LoadCountriesFailed:return Tf(e,"loadError",t.payload);default:return e}}function Vv(e=jv.statuses,t){switch(t.type){case Dm.LoadCountriesRequested:return Tf(e,"isLoading",!0);case Dm.LoadCountriesSucceeded:case Dm.LoadCountriesFailed:return Tf(e,"isLoading",!1);default:return e}}const Gv={errors:{},meta:{},statuses:{}};function Hv(e=Gv,t){return d({data:Wv,errors:c(Yv,Ef),meta:$v,statuses:Kv})(e,t)}function Wv(e,t){switch(t.type){case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:return qf(e,le(t.payload,["billingAddress","coupons"]));default:return e}}function $v(e,t){switch(t.type){case Mm.FinalizeOrderSucceeded:case Mm.SubmitOrderSucceeded:return qf(e,Object.assign(Object.assign({},t.meta),{callbackUrl:t.payload&&t.payload.order.callbackUrl,orderToken:t.payload&&t.payload.order.token,payment:t.payload&&t.payload.order&&t.payload.order.payment}));default:return e}}function Yv(e=Gv.errors,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderSucceeded:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsRequested:return Tf(e,"loadError",void 0);case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsFailed:return Tf(e,"loadError",t.payload);default:return e}}function Kv(e=Gv.statuses,t){switch(t.type){case Mm.LoadOrderRequested:case Mm.LoadOrderPaymentsRequested:return Tf(e,"isLoading",!0);case Mm.LoadOrderSucceeded:case Mm.LoadOrderFailed:case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderPaymentsFailed:return Tf(e,"isLoading",!1);default:return e}}const Jv={};function Zv(e=Jv,t){return d({data:Qv})(e,t)}function Qv(e,t){switch(t.type){case Mm.LoadOrderPaymentsSucceeded:case Mm.LoadOrderSucceeded:return Nf(e,t.payload&&t.payload.billingAddress);default:return e}}function Xv(e={},t){return d({data:e_})(e,t)}function e_(e,t){return t.type===fy.SubmitPaymentSucceeded?t.payload:e}const t_={errors:{},statuses:{}};function n_(e=t_,t){return d({data:i_,errors:c(o_,Ef),meta:r_,statuses:a_})(e,t)}function i_(e,t){switch(t.type){case qm.LoadPaymentMethodSucceeded:return function(e,t,n){if(!t)return e;const i=pe(t,"id"),r="object"==typeof n?me(n):n||i,o=B(e,r),a=[...e];if(-1===o)a.push(t);else{const n=e[o];a[o]=Lg(n)&&Lg(t)?qf(n,t):t}return a}(e||[],t.payload,t.payload&&{id:t.payload.id,gateway:t.payload.gateway});case qm.LoadPaymentMethodsSucceeded:return Uf(e,t.payload,{matchObject:(e,t)=>e.id===t.id&&e.gateway===t.gateway});default:return e}}function r_(e,t){return t.type===qm.LoadPaymentMethodsSucceeded?qf(e,t.meta):e}function o_(e=t_.errors,t){switch(t.type){case qm.LoadPaymentMethodsRequested:case qm.LoadPaymentMethodsSucceeded:return Tf(e,"loadError",void 0);case qm.LoadPaymentMethodsFailed:return Tf(e,"loadError",t.payload);case qm.LoadPaymentMethodRequested:case qm.LoadPaymentMethodSucceeded:return qf(e,{loadMethodId:void 0,loadMethodError:void 0});case qm.LoadPaymentMethodFailed:return qf(e,{loadMethodId:t.meta.methodId,loadMethodError:t.payload});default:return e}}function a_(e=t_.statuses,t){switch(t.type){case qm.LoadPaymentMethodsRequested:return Tf(e,"isLoading",!0);case qm.LoadPaymentMethodsSucceeded:case qm.LoadPaymentMethodsFailed:return Tf(e,"isLoading",!1);case qm.LoadPaymentMethodRequested:return qf(e,{isLoadingMethod:!0,loadMethodId:t.meta.methodId});case qm.LoadPaymentMethodSucceeded:case qm.LoadPaymentMethodFailed:return qf(e,{isLoadingMethod:!1,loadMethodId:void 0});default:return e}}const s_={data:{},errors:{},statuses:{}};function d_(e=s_,t){return d({data:c_,errors:c(l_,Ef),statuses:u_})(e,t)}function c_(e=s_.data,t){switch(t.type){case Km.InitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return qf(e,{[r]:{isInitialized:!0}})}break;case Km.DeinitializeSucceeded:if(t.meta){const{methodId:n,gatewayId:i}=t.meta,r=i?`${n}.${i}`:n;return qf(e,{[r]:{isInitialized:!1}})}}return e}function l_(e=s_.errors,t){switch(t.type){case Km.InitializeRequested:case Km.InitializeSucceeded:return qf(e,{initializeError:void 0,initializeMethodId:void 0});case Km.InitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return qf(e,{initializeError:t.payload,initializeMethodId:n})}case Km.DeinitializeRequested:case Km.DeinitializeSucceeded:return qf(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Km.DeinitializeFailed:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return qf(e,{deinitializeError:t.payload,deinitializeMethodId:n})}case Km.ExecuteRequested:case Km.ExecuteSucceeded:return qf(e,{executeError:void 0,executeMethodId:void 0});case Km.ExecuteFailed:return qf(e,{executeError:t.payload,executeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeRequested:case Km.FinalizeSucceeded:return qf(e,{finalizeError:void 0,finalizeMethodId:void 0});case Km.FinalizeFailed:return qf(e,{finalizeError:t.payload,finalizeMethodId:t.meta&&t.meta.methodId});case Km.WidgetInteractionStarted:case Km.WidgetInteractionFinished:return qf(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Km.WidgetInteractionFailed:return qf(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function u_(e=s_.statuses,t){switch(t.type){case Km.InitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return qf(e,{isInitializing:!0,initializeMethodId:n})}case Km.InitializeFailed:case Km.InitializeSucceeded:return qf(e,{isInitializing:!1,initializeMethodId:void 0});case Km.DeinitializeRequested:{let n=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:i}=t.meta;n=i?`${e}.${i}`:e}return qf(e,{isDeinitializing:!0,deinitializeMethodId:n})}case Km.DeinitializeFailed:case Km.DeinitializeSucceeded:return qf(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Km.ExecuteRequested:return qf(e,{isExecuting:!0,executeMethodId:t.meta&&t.meta.methodId});case Km.ExecuteFailed:case Km.ExecuteSucceeded:return qf(e,{isExecuting:!1,executeMethodId:void 0});case Km.FinalizeRequested:return qf(e,{isFinalizing:!0,finalizeMethodId:t.meta&&t.meta.methodId});case Km.FinalizeFailed:case Km.FinalizeSucceeded:return qf(e,{isFinalizing:!1,finalizeMethodId:void 0});case Km.WidgetInteractionStarted:return qf(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Km.WidgetInteractionFinished:case Km.WidgetInteractionFailed:return qf(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const h_={data:{}};function p_(e=h_,t){return d({data:m_})(e,t)}function m_(e=h_.data,t){return t.type===mg.UpdatePaymentProviderCustomer?qf(e,t.payload):e}const y_={data:[],errors:{},statuses:{}};function g_(e=y_,t){return d({data:f_,errors:c(__,Ef),meta:v_,statuses:S_})(e,t)}function f_(e=y_.data,t){return t.type===Vg.LoadInstrumentsSucceeded?Uf(e,t.payload&&t.payload.vaultedInstruments||[]):e}function v_(e,t){switch(t.type){case Vg.LoadInstrumentsSucceeded:case Vg.DeleteInstrumentSucceeded:return qf(e,t.meta);default:return e}}function __(e=y_.errors,t){switch(t.type){case Vg.LoadInstrumentsRequested:case Vg.LoadInstrumentsSucceeded:return Tf(e,"loadError",void 0);case Vg.DeleteInstrumentRequested:case Vg.DeleteInstrumentSucceeded:return qf(e,{deleteError:void 0,failedInstrument:void 0});case Vg.LoadInstrumentsFailed:return Tf(e,"loadError",t.payload);case Vg.DeleteInstrumentFailed:return qf(e,{deleteError:t.payload,failedInstrument:t.meta.instrumentId});default:return e}}function S_(e=y_.statuses,t){switch(t.type){case Vg.LoadInstrumentsRequested:return Tf(e,"isLoading",!0);case Vg.DeleteInstrumentRequested:return qf(e,{isDeleting:!0,deletingInstrument:t.meta.instrumentId});case Vg.LoadInstrumentsSucceeded:case Vg.LoadInstrumentsFailed:return Tf(e,"isLoading",!1);case Vg.DeleteInstrumentSucceeded:case Vg.DeleteInstrumentFailed:return qf(e,{isDeleting:!1,deletingInstrument:void 0});default:return e}}const I_={data:{}};function w_(e=I_,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:C_})})(e,t):e}function C_(e,t){switch(t.type){case yg.InitializeRemoteBillingSucceeded:return Tf(e,"billing",t.payload&&t.payload.billing);case yg.InitializeRemoteShippingSucceeded:return Tf(e,"shipping",t.payload&&t.payload.shipping);case yg.LoadRemoteSettingsSucceeded:return Tf(e,"settings",t.payload);case yg.UpdateRemoteCheckout:return qf(e,t.payload);default:return e}}const b_={errors:{updateShippingOptionError:{},updateError:{},deleteError:{}},statuses:{isUpdating:{},isUpdatingShippingOption:{},isDeleting:{}}};function P_(e=b_,t){return d({data:O_,errors:c(E_,Ef),statuses:A_})(e,t)}function O_(e,t){var n,i;switch(t.type){case Yt.LoadCheckoutSucceeded:case wg.LoadShippingOptionsSucceeded:case wg.CreateConsignmentsSucceeded:case wg.UpdateConsignmentSucceeded:case wg.DeleteConsignmentSucceeded:case wg.UpdateShippingOptionSucceeded:case Dt.ApplyCouponSucceeded:case Dt.RemoveCouponSucceeded:return Uf(e,t.payload&&t.payload.consignments);case Ft.SignOutCustomerSucceeded:return Uf(e,[]);case Kt.HydrateInitialState:return Uf(e,null===(i=null===(n=t.payload)||void 0===n?void 0:n.checkout)||void 0===i?void 0:i.consignments);default:return e}}function E_(e=b_.errors,t){switch(t.type){case Yt.LoadCheckoutRequested:case Yt.LoadCheckoutSucceeded:case wg.LoadShippingOptionsSucceeded:case wg.LoadShippingOptionsRequested:return Tf(e,"loadError",void 0);case Yt.LoadCheckoutFailed:case wg.LoadShippingOptionsFailed:return Tf(e,"loadError",t.payload);case wg.CreateConsignmentsRequested:case wg.CreateConsignmentsSucceeded:return Tf(e,"createError",void 0);case wg.CreateConsignmentsFailed:return Tf(e,"createError",t.payload);case wg.UpdateConsignmentSucceeded:case wg.UpdateConsignmentRequested:return t.meta?qf(e,{updateError:{[t.meta.id]:void 0}}):e;case wg.UpdateConsignmentFailed:return t.meta?qf(e,{updateError:{[t.meta.id]:t.payload}}):e;case wg.DeleteConsignmentSucceeded:case wg.DeleteConsignmentRequested:return t.meta?qf(e,{deleteError:{[t.meta.id]:void 0}}):e;case wg.DeleteConsignmentFailed:return t.meta?qf(e,{deleteError:{[t.meta.id]:t.payload}}):e;case wg.UpdateShippingOptionRequested:case wg.UpdateShippingOptionSucceeded:return t.meta?qf(e,{updateShippingOptionError:{[t.meta.id]:void 0}}):e;case wg.UpdateShippingOptionFailed:return t.meta?qf(e,{updateShippingOptionError:{[t.meta.id]:t.payload}}):e;default:return e}}function A_(e=b_.statuses,t){switch(t.type){case Yt.LoadCheckoutRequested:return Tf(e,"isLoading",!0);case wg.LoadShippingOptionsRequested:return Tf(e,"isLoadingShippingOptions",!0);case Yt.LoadCheckoutSucceeded:case Yt.LoadCheckoutFailed:return Tf(e,"isLoading",!1);case wg.LoadShippingOptionsSucceeded:case wg.LoadShippingOptionsFailed:return Tf(e,"isLoadingShippingOptions",!1);case wg.CreateConsignmentsRequested:return Tf(e,"isCreating",!0);case wg.CreateConsignmentsSucceeded:case wg.CreateConsignmentsFailed:return Tf(e,"isCreating",!1);case wg.UpdateConsignmentRequested:return t.meta?qf(e,{isUpdating:{[t.meta.id]:!0}}):e;case wg.UpdateConsignmentSucceeded:case wg.UpdateConsignmentFailed:return t.meta?qf(e,{isUpdating:{[t.meta.id]:!1}}):e;case wg.DeleteConsignmentRequested:return t.meta?qf(e,{isDeleting:{[t.meta.id]:!0}}):e;case wg.DeleteConsignmentSucceeded:case wg.DeleteConsignmentFailed:return t.meta?qf(e,{isDeleting:{[t.meta.id]:!1}}):e;case wg.UpdateShippingOptionRequested:return t.meta?qf(e,{isUpdatingShippingOption:{[t.meta.id]:!0}}):e;case wg.UpdateShippingOptionSucceeded:case wg.UpdateShippingOptionFailed:return t.meta?qf(e,{isUpdatingShippingOption:{[t.meta.id]:!1}}):e;default:return e}}function T_(e,t){const n={};return Object.keys(e).forEach(i=>{const r=e[i],o=t?`${t}.${i}`:i;"object"==typeof r?Object.assign(n,T_(r,o)):n[o]=r}),n}function k_(e){return Object.keys(e).sort().reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]}),{})}const D_={errors:{},statuses:{}};function M_(e=D_,t){return d({data:z_,errors:c(x_,Ef),statuses:N_})(e,t)}function z_(e,t){if(t.type!==Kg.LoadPickupOptionsSucceeded)return e;if(t.meta){const n=k_(T_({consignmentId:t.meta.consignmentId,searchArea:t.meta.searchArea}));return Tf(e,btoa(`${JSON.stringify(n)}`),t.payload)}}function x_(e=D_.errors,t){switch(t.type){case Kg.LoadPickupOptionsRequested:case Kg.LoadPickupOptionsSucceeded:return Tf(e,"loadError",void 0);case Kg.LoadPickupOptionsFailed:return Tf(e,"loadError",t.payload);default:return e}}function N_(e=D_.statuses,t){switch(t.type){case Kg.LoadPickupOptionsRequested:return Tf(e,"isLoading",!0);case Kg.LoadPickupOptionsSucceeded:case Kg.LoadPickupOptionsFailed:return Tf(e,"isLoading",!1);default:return e}}const R_={errors:{},statuses:{}};function F_(e=R_,t){return d({data:L_,errors:c(j_,Ef),statuses:B_})(e,t)}function L_(e,t){return t.type===Ag.LoadShippingCountriesSucceeded?Uf(e,t.payload):e}function j_(e=R_.errors,t){switch(t.type){case Ag.LoadShippingCountriesRequested:case Ag.LoadShippingCountriesSucceeded:return Tf(e,"loadError",void 0);case Ag.LoadShippingCountriesFailed:return Tf(e,"loadError",t.payload);default:return e}}function B_(e=R_.statuses,t){switch(t.type){case Ag.LoadShippingCountriesRequested:return Tf(e,"isLoading",!0);case Ag.LoadShippingCountriesSucceeded:case Ag.LoadShippingCountriesFailed:return Tf(e,"isLoading",!1);default:return e}}const U_={data:{},errors:{},statuses:{}};function q_(e=U_,t){return d({data:V_,errors:c(G_,Ef),statuses:H_})(e,t)}function V_(e=U_.data,t){switch(t.type){case Jg.InitializeSucceeded:return qf(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Jg.DeinitializeSucceeded:return qf(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function G_(e=U_.errors,t){switch(t.type){case Jg.InitializeRequested:case Jg.InitializeSucceeded:return qf(e,{initializeError:void 0,initializeMethodId:void 0});case Jg.InitializeFailed:return qf(e,{initializeError:t.payload,initializeMethodId:t.meta&&t.meta.methodId});case Jg.DeinitializeRequested:case Jg.DeinitializeSucceeded:return qf(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Jg.DeinitializeFailed:return qf(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Jg.UpdateAddressRequested:case Jg.UpdateAddressSucceeded:return qf(e,{updateAddressError:void 0,updateAddressMethodId:void 0});case Jg.UpdateAddressFailed:return qf(e,{updateAddressError:t.payload,updateAddressMethodId:t.meta&&t.meta.methodId});case Jg.SelectOptionRequested:case Jg.SelectOptionSucceeded:return qf(e,{selectOptionError:void 0,selectOptionMethodId:void 0});case Jg.SelectOptionFailed:return qf(e,{selectOptionError:t.payload,selectOptionMethodId:t.meta&&t.meta.methodId});case Jg.WidgetInteractionStarted:case Jg.WidgetInteractionFinished:return qf(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Jg.WidgetInteractionFailed:return qf(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta&&t.meta.methodId});default:return e}}function H_(e=U_.statuses,t){switch(t.type){case Jg.InitializeRequested:return qf(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Jg.InitializeFailed:case Jg.InitializeSucceeded:return qf(e,{isInitializing:!1,initializeMethodId:void 0});case Jg.DeinitializeRequested:return qf(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Jg.DeinitializeFailed:case Jg.DeinitializeSucceeded:return qf(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Jg.UpdateAddressRequested:return qf(e,{isUpdatingAddress:!0,updateAddressMethodId:t.meta&&t.meta.methodId});case Jg.UpdateAddressFailed:case Jg.UpdateAddressSucceeded:return qf(e,{isUpdatingAddress:!1,updateAddressMethodId:void 0});case Jg.SelectOptionRequested:return qf(e,{isSelectingOption:!0,selectOptionMethodId:t.meta&&t.meta.methodId});case Jg.SelectOptionFailed:case Jg.SelectOptionSucceeded:return qf(e,{isSelectingOption:!1,selectOptionMethodId:void 0});case Jg.WidgetInteractionStarted:return qf(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta&&t.meta.methodId});case Jg.WidgetInteractionFinished:case Jg.WidgetInteractionFailed:return qf(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const W_={errors:{},statuses:{}};function $_(e=W_,t){return d({data:Y_,errors:c(K_,Ef),statuses:J_})(e,t)}function Y_(e,t){return t.type===hf.SendSignInEmailSucceeded?qf(e,t.payload):e}function K_(e=W_.errors,t){switch(t.type){case hf.SendSignInEmailRequested:case hf.SendSignInEmailSucceeded:return Tf(e,"sendError",void 0);case hf.SendSignInEmailFailed:return Tf(e,"sendError",t.payload);default:return e}}function J_(e=W_.statuses,t){switch(t.type){case hf.SendSignInEmailRequested:return Tf(e,"isSending",!0);case hf.SendSignInEmailFailed:case hf.SendSignInEmailSucceeded:return Tf(e,"isSending",!1);default:return e}}const Z_={errors:{},statuses:{}};function Q_(e=Z_,t){return d({errors:c(X_,Ef),statuses:eS})(e,t)}function X_(e=Z_.errors,t){switch(t.type){case Tg.ApplyStoreCreditRequested:case Tg.ApplyStoreCreditSucceeded:return Tf(e,"applyError",void 0);case Tg.ApplyStoreCreditFailed:return Tf(e,"applyError",t.payload);default:return e}}function eS(e=Z_.statuses,t){switch(t.type){case Tg.ApplyStoreCreditRequested:return Tf(e,"isApplying",!0);case Tg.ApplyStoreCreditSucceeded:case Tg.ApplyStoreCreditFailed:return Tf(e,"isApplying",!1);default:return e}}const tS={errors:{},statuses:{}};function nS(e=tS,t){return d({errors:c(iS,Ef),statuses:rS})(e,t)}function iS(e=tS.errors,t){switch(t.type){case Mg.UpdateSubscriptionsRequested:case Mg.UpdateSubscriptionsSucceeded:return Tf(e,"updateError",void 0);case Mg.UpdateSubscriptionsFailed:return Tf(e,"updateError",t.payload);default:return e}}function rS(e=tS.statuses,t){switch(t.type){case Mg.UpdateSubscriptionsRequested:return Tf(e,"isUpdating",!0);case Mg.UpdateSubscriptionsFailed:case Mg.UpdateSubscriptionsSucceeded:return Tf(e,"isUpdating",!1);default:return e}}const oS={errors:{},statuses:{}};function aS(e=oS,t){return d({data:sS,errors:c(dS,Ef),statuses:cS})(e,t)}function sS(e,t){var n;switch(t.type){case Yt.LoadCheckoutSucceeded:case Yt.UpdateCheckoutSucceeded:case Tg.ApplyStoreCreditSucceeded:case nt.UpdateBillingAddressSucceeded:case Dt.ApplyCouponSucceeded:case Dt.RemoveCouponSucceeded:case wg.CreateConsignmentsSucceeded:case wg.UpdateConsignmentSucceeded:case wg.DeleteConsignmentSucceeded:case wg.UpdateShippingOptionSucceeded:case wg.LoadShippingOptionsSucceeded:case Nt.ApplyGiftCertificateSucceeded:case Nt.RemoveGiftCertificateSucceeded:case on.VerifyCheckoutSucceeded:return qf(e,le(t.payload,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));case Mm.SubmitOrderSucceeded:return Tf(e,"orderId",t.payload&&t.payload.order.orderId);case Kt.HydrateInitialState:return qf(e,le(null===(n=t.payload)||void 0===n?void 0:n.checkout,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));default:return e}}function dS(e=oS.errors,t){switch(t.type){case Yt.LoadCheckoutRequested:case Yt.LoadCheckoutSucceeded:return Tf(e,"loadError",void 0);case Yt.LoadCheckoutFailed:return Tf(e,"loadError",t.payload);case Yt.UpdateCheckoutRequested:case Yt.UpdateCheckoutSucceeded:return Tf(e,"updateError",void 0);case Yt.UpdateCheckoutFailed:return Tf(e,"updateError",t.payload);default:return e}}function cS(e=oS.statuses,t){switch(t.type){case Yt.LoadCheckoutRequested:return Tf(e,"isLoading",!0);case Yt.LoadCheckoutFailed:case Yt.LoadCheckoutSucceeded:return Tf(e,"isLoading",!1);case Yt.UpdateCheckoutRequested:return Tf(e,"isUpdating",!0);case Yt.UpdateCheckoutFailed:case Yt.UpdateCheckoutSucceeded:return Tf(e,"isUpdating",!1);case on.ExecuteRequested:return Tf(e,"isExecutingSpamCheck",!0);case on.ExecuteFailed:case on.ExecuteSucceeded:return Tf(e,"isExecutingSpamCheck",!1);default:return e}}function lS(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}function uS(e){return function(e){const t=Object.create(e);return function(e,t){let n=Object.getPrototypeOf(e);for(;n;)t(n),n=Object.getPrototypeOf(n)}(e,n=>{Object.getOwnPropertyNames(n).forEach(n=>{"constructor"!==n&&"function"==typeof t[n]&&"_"!==n.charAt(0)&&(t[n]=((e,t)=>(...n)=>p(e[t].call(e,...n)))(e,n))})}),t}(e)}const hS={"mollie.credit_card":{provider:"mollie",method:"credit_card"},"adyenv2.scheme":{provider:"adyenv2",method:"scheme"},"adyenv3.scheme":{provider:"adyenv3",method:"scheme"},"adyenv2.bcmc":{provider:"adyenv2",method:"bcmc"},"adyenv2.ideal":{provider:"adyenv2",method:"ideal"},"adyenv2.sepadirectdebit":{provider:"adyenv2",method:"sepadirectdebit"},"adyenv2.directEbanking":{provider:"adyenv2",method:"directEbanking"},"adyenv2.giropay":{provider:"adyenv2",method:"giropay"},braintree:{provider:"braintree",method:"credit_card"},braintreepaypal:{provider:"braintree",method:"paypal"},braintreeach:{provider:"braintree",method:"ach"},authorizenet:{provider:"authorizenet",method:"credit_card"},elavon:{provider:"elavon",method:"credit_card"},checkoutcom:{provider:"checkoutcom",method:"credit_card"},"checkoutcom.credit_card":{provider:"checkoutcom",method:"credit_card"},"checkoutcom.card":{provider:"checkoutcom",method:"card"},sagepay:{provider:"sagepay",method:"credit_card"},stripe:{provider:"stripe",method:"credit_card"},"stripev3.card":{provider:"stripev3",method:"card"},"stripeupe.card":{provider:"stripeupe",method:"card"},cybersource:{provider:"cybersource",method:"credit_card"},cybersourcev2:{provider:"cybersourcev2",method:"credit_card"},bnz:{provider:"bnz",method:"credit_card"},converge:{provider:"converge",method:"credit_card"},bluesnapv2:{provider:"bluesnapv2",method:"credit_card"},"bluesnapdirect.credit_card":{provider:"bluesnapdirect",method:"credit_card"},"bluesnapdirect.ecp":{provider:"bluesnapdirect",method:"ecp"},"bluesnapdirect.sepa_direct_debit":{provider:"bluesnapdirect",method:"sepa_direct_debit"},orbital:{provider:"orbital",method:"credit_card"},paymetric:{provider:"paymetric",method:"credit_card"},bolt:{provider:"bolt",method:"credit_card"},"barclaycard.credit_card":{provider:"barclaycard",method:"credit_card"},moneris:{provider:"moneris",method:"credit_card"},cba_mpgs:{provider:"cba_mpgs",method:"credit_card"},worldpayaccess:{provider:"worldpayaccess",method:"credit_card"},"worldpayaccess.credit_card":{provider:"worldpayaccess",method:"credit_card"},squarev2:{provider:"squarev2",method:"credit_card"},paypalcommercecreditcards:{provider:"paypalcommerce",method:"credit_card"},paypalcommerce:{provider:"paypalcommerce",method:"paypal"},bigcommerce_payments_creditcards:{provider:"bigcommerce_payments",method:"credit_card"},bigcommerce_payments:{provider:"bigcommerce_payments",method:"paypal"},tdonlinemart:{provider:"tdonlinemart",method:"credit_card"}};function pS(e){return me({firstName:e.firstName,lastName:e.lastName,company:e.company,address1:e.address1,address2:e.address2,city:e.city,stateOrProvince:e.stateOrProvince,countryCode:e.countryCode,postalCode:e.postalCode,phone:e.phone,customFields:e.customFields},G)}const mS={errors:{},statuses:{}};function yS(){const e=function(){const e=Sf(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.token},e=>()=>e),t=Sf(e=>e.errors.loadError,e=>()=>e),n=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=kf)=>({getToken:e(i),getLoadError:t(i),isLoading:n(i)}))}(),t=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingBillingAddress))),n=Sf(e=>e.errors.updateError,e=>()=>e),i=Sf(e=>e.errors.continueAsGuestError,e=>()=>e),r=Sf(e=>e.errors.loadError,e=>()=>e),o=Sf(e=>!!e.statuses.isUpdating,e=>()=>e),a=Sf(e=>!!e.statuses.isContinuingAsGuest,e=>()=>e),s=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((d=Rf)=>({getBillingAddress:e(d),getBillingAddressOrThrow:t(d),getUpdateError:n(d),getContinueAsGuestError:i(d),getLoadError:r(d),isUpdating:o(d),isContinuingAsGuest:a(d),isLoading:s(d)}))}(),n=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingCart))),n=Sf(e=>e.errors.loadError,e=>()=>e),i=Sf(e=>!!e.statuses.isLoading,e=>()=>e),r=Sf(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.locale},e=>()=>e);return Oe((o=Vf)=>({getCart:e(o),getCartOrThrow:t(o),getLoadError:n(o),isLoading:i(o),getLocale:r(o)}))}(),i=function(){const e=Sf(e=>e,e=>()=>e),t=Sf(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isInitializing)}return fe(e,{isInitializing:!0})})),n=Sf(e=>e.data,e=>Pe((t,n)=>{const i=e[t];return!!i&&(n?!0===i.initializedContainers[n]:fe(i.initializedContainers,e=>!0===e))})),i=Sf(e=>e.statuses,e=>Pe(t=>{if(t){const n=e[t];return!0===(n&&n.isDeinitializing)}return fe(e,{isDeinitializing:!0})})),r=Sf(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:j(Ce(e),e=>!(!e||!e.initializeError));return n&&n.initializeError})),o=Sf(e=>e.errors,e=>Pe(t=>{const n=t?e[t]:j(Ce(e),e=>!(!e||!e.deinitializeError));return n&&n.deinitializeError}));return Oe((a=Kf)=>({getState:e(a),isInitializing:t(a),isInitialized:n(a),isDeinitializing:i(a),getInitializeError:r(a),getDeinitializeError:o(a)}))}(),r=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.data,e=>t=>{if(!e)return;const{flashMessages:n}=e.context;return n?void 0!==t?n.filter(({type:e})=>t===e):n:void 0}),n=Sf(e=>e.data,(e,{formState:t})=>t&&t.data,(e,t={customerAccount:[],shippingAddress:[],billingAddress:[]})=>()=>e?Object.assign(Object.assign({},e.storeConfig),{formFields:t}):void 0),i=Sf(n,e=>()=>lS(e(),()=>new ot(tt.MissingCheckoutConfig))),r=Sf(e=>e.data&&e.data.context,e=>()=>e),o=Sf(e=>e.meta&&e.meta.externalSource,e=>()=>e),a=Sf(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.host},e=>()=>e),s=Sf(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.locale},e=>()=>e),d=Sf(e=>e.meta&&e.meta.variantIdentificationToken,e=>()=>e),c=Sf(e=>e.errors.loadError,e=>()=>e),l=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((u=iv,h)=>({getConfig:e(u),getFlashMessages:t(u),getStoreConfig:n(u,{formState:h}),getStoreConfigOrThrow:i(u,{formState:h}),getContextConfig:r(u),getExternalSource:o(u),getHost:a(u),getLocale:s(u),getVariantIdentificationToken:d(u),getLoadError:c(u),isLoading:l(u)}))}(),o=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.errors.loadError,e=>()=>e),n=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=jv)=>({getCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),a=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.errors.removeCouponError,e=>()=>e),n=Sf(e=>e.errors.applyCouponError,e=>()=>e),i=Sf(e=>!!e.statuses.isApplyingCoupon,e=>()=>e),r=Sf(e=>!!e.statuses.isRemovingCoupon,e=>()=>e);return Oe((o=dv)=>({getCoupons:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),s=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingCustomer))),n=Sf(e=>e.errors.createError,e=>()=>e),i=Sf(e=>!!e.statuses.isCreating,e=>()=>e),r=Sf(e=>e.errors.createAddressError,e=>()=>e),o=Sf(e=>!!e.statuses.isCreatingAddress,e=>()=>e);return Oe((a=vv)=>({getCustomer:e(a),getCustomerOrThrow:t(a),getCreateAccountError:n(a),isCreatingCustomerAccount:i(a),getCreateAddressError:r(a),isCreatingCustomerAddress:o(a)}))}(),d=function(){const e=Sf(e=>e.errors.signInMethodId,e=>e.errors.signInError,(e,t)=>n=>{if(!n||e===n)return t}),t=Sf(e=>e.errors.signOutMethodId,e=>e.errors.signOutError,(e,t)=>n=>{if(!n||e===n)return t}),n=Sf(e=>e.errors.executePaymentMethodCheckoutMethodId,e=>e.errors.executePaymentMethodCheckoutError,(e,t)=>n=>{if(!n||e===n)return t}),i=Sf(e=>e.errors.initializeMethodId,e=>e.errors.initializeErrors,(e,t)=>n=>{if(e&&t)return n?t[n]:t[e]}),r=Sf(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),o=Sf(e=>e.statuses.signInMethodId,e=>e.statuses.isSigningIn,(e,t)=>n=>!(n&&e!==n||!t)),a=Sf(e=>e.statuses.signOutMethodId,e=>e.statuses.isSigningOut,(e,t)=>n=>!(n&&e!==n||!t)),s=Sf(e=>e.statuses.executePaymentMethodCheckoutMethodId,e=>e.statuses.isExecutingPaymentMethodCheckout,(e,t)=>n=>!(n&&e!==n||!t)),d=Sf(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),c=Sf(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),l=Sf(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((u=Cv)=>({getSignInError:e(u),getSignOutError:t(u),getExecutePaymentMethodCheckoutError:n(u),getInitializeError:i(u),getWidgetInteractionError:r(u),isSigningIn:o(u),isSigningOut:a(u),isExecutingPaymentMethodCheckout:s(u),isInitializing:d(u),isInitialized:c(u),isWidgetInteracting:l(u)}))}(),c=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.errors.removeGiftCertificateError,e=>()=>e),n=Sf(e=>e.errors.applyGiftCertificateError,e=>()=>e),i=Sf(e=>!!e.statuses.isApplyingGiftCertificate,e=>()=>e),r=Sf(e=>!!e.statuses.isRemovingGiftCertificate,e=>()=>e);return Oe((o=pv)=>({getGiftCertificates:e(o),getRemoveError:t(o),getApplyError:n(o),isApplying:i(o),isRemoving:r(o)}))}(),l=function(){const e=Sf(e=>e.data,e=>t=>{if(!e)return;const n=t.gateway?`${t.gateway}.${t.id}`:t.id,i=hS[n];return i?L(e,i):[]}),t=Sf(e=>e.data,(e=[])=>t=>{const n=Ce(hS);return e.find(e=>e.bigpayToken===t&&"card"===e.type&&n.some(t=>K(e,t)))}),n=Sf(t,e=>t=>lS(e(t),()=>new ot(tt.MissingPaymentInstrument))),i=Sf(e=>e.data,e=>()=>{if(e)return U(hS,t=>L(e,e=>K(e,t)))}),r=Sf(e=>e.meta,e=>()=>e),o=Sf(e=>e.errors.loadError,e=>()=>e),a=Sf(e=>e.errors.failedInstrument,e=>e.errors.deleteError,(e,t)=>n=>{if(!n||e===n)return t}),s=Sf(e=>e.statuses.isLoading,e=>()=>!!e),d=Sf(e=>e.statuses.deletingInstrument,e=>e.statuses.isDeleting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=y_)=>({getCardInstrument:t(c),getCardInstrumentOrThrow:n(c),getInstruments:i(c),getInstrumentsByPaymentMethod:e(c),getInstrumentsMeta:r(c),getLoadError:o(c),getDeleteError:a(c),isLoading:s(c),isDeleting:d(c)}))}(),u=function(){const e=Sf(e=>e.data,e=>(t=[],n)=>{const i=j(t,{code:n});return(e?e.shippingAddress:[]).map(e=>a(e,t,i))}),t=Sf(e=>e.data,e=>(t=[],n)=>{const i=j(t,{code:n});return(e?e.billingAddress:[]).map(e=>a(e,t,i))}),n=Sf(e=>e.data,e=>()=>e?e.customerAccount:[]),i=Sf(e=>e.extraFields,e=>()=>e&&e.address.length?e.address.map(Ye):[]),r=Sf(e=>e.errors.loadError,e=>()=>e),o=Sf(e=>!!e.statuses.isLoading,e=>()=>e);function a(e,t,n){return"countryCode"===e.name?function(e,t=[],n){if(!t.length)return e;const{code:i=""}=n||{},r=t.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{options:{items:r},default:i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,t,n):"stateOrProvince"===e.name?function(e,t){const{subdivisions:n=[],requiresState:i}=t||{};if(!n.length)return Object.assign(Object.assign({},e),{required:null!=i&&i});const r=n.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{name:"stateOrProvinceCode",options:{items:r},required:null==i||i,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,n):"postalCode"===e.name?function(e,t){const{hasPostalCodes:n=[]}=t||{};return void 0===n?e:Object.assign(Object.assign({},e),{required:Boolean(n)})}(e,n):e}return Oe((a=zv)=>({getShippingAddressFields:e(a),getBillingAddressFields:t(a),getCustomerAccountFields:n(a),getAddressExtraFields:i(a),getLoadError:r(a),isLoading:o(a)}))}(),h=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.meta,e=>()=>e),n=Sf(e=>e.data,e=>(t,n)=>j(e,n?{id:t,gateway:n}:{id:t})),i=Sf(n,e=>(t,n)=>lS(e(t,n),()=>new ot(tt.MissingPaymentMethod))),r=Sf(e=>e.errors.loadError,e=>()=>e),o=Sf(e=>e.errors.loadMethodId,e=>e.errors.loadMethodError,(e,t)=>n=>{if(!n||e===n)return t}),a=Sf(e=>e.statuses.isLoading,e=>()=>!!e),s=Sf(e=>e.statuses.loadMethodId,e=>e.statuses.isLoadingMethod,(e,t)=>n=>!(n&&e!==n||!t));return Oe((d=t_)=>({getPaymentMethods:e(d),getPaymentMethodsMeta:t(d),getPaymentMethod:n(d),getPaymentMethodOrThrow:i(d),getLoadError:r(d),getLoadMethodError:o(d),isLoading:a(d),isLoadingMethod:s(d)}))}(),p=function(){const e=Sf(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),t=Sf(e=>e.errors.executeMethodId,e=>e.errors.executeError,(e,t)=>n=>{if(!n||e===n)return t}),n=Sf(e=>e.errors.finalizeMethodId,e=>e.errors.finalizeError,(e,t)=>n=>{if(!n||e===n)return t}),i=Sf(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=Sf(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),o=Sf(e=>e.data,e=>t=>{const n=t.gatewayId?`${t.methodId}.${t.gatewayId}`:t.methodId;return!(!e[n]||!e[n].isInitialized)}),a=Sf(e=>e.statuses.executeMethodId,e=>e.statuses.isExecuting,(e,t)=>n=>!(n&&e!==n||!t)),s=Sf(e=>e.statuses.finalizeMethodId,e=>e.statuses.isFinalizing,(e,t)=>n=>!(n&&e!==n||!t)),d=Sf(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=s_)=>({getInitializeError:e(c),getExecuteError:t(c),getFinalizeError:n(c),getWidgetInteractingError:i(c),isInitializing:r(c),isInitialized:o(c),isExecuting:a(c),isFinalizing:s(c),isWidgetInteracting:d(c)}))}(),m=function(){const e=Sf(e=>e.data,e=>(t,n)=>{if(!e)return;const i=k_(T_({consignmentId:t,searchArea:n})),r=btoa(`${JSON.stringify(i)}`);return e[r]}),t=Sf(e=>e.errors.loadError,e=>()=>e),n=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((i=D_)=>({getPickupOptions:e(i),getLoadError:t(i),isLoading:n(i)}))}(),y=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingPaymentProviderCustomer)));return Oe((n=h_)=>({getPaymentProviderCustomer:e(n),getPaymentProviderCustomerOrThrow:t(n)}))}(),g=function(){const e=Sf(e=>e.data,e=>t=>e[t]);return Oe((t=I_)=>({getCheckout:e(t)}))}(),f=function(){const e=Sf(e=>e.data,e=>()=>{const t=null==e?void 0:e.find(e=>!e.selectedPickupOption);return null==t?void 0:t.shippingAddress}),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingShippingAddress))),n=Sf(e=>e.data,e=>()=>{const t=null==e?void 0:e.filter(e=>!e.selectedPickupOption);return t?t.map(e=>e.shippingAddress):[]}),i=Sf(n,e=>()=>lS(e(),()=>new ot(tt.MissingShippingAddress)));return Oe((r=b_)=>({getShippingAddress:e(r),getShippingAddressOrThrow:t(r),getShippingAddresses:n(r),getShippingAddressesOrThrow:i(r)}))}(),v=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.errors.loadError,e=>()=>e),n=Sf(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((i=R_)=>({getShippingCountries:e(i),getLoadError:t(i),isLoading:n(i)}))}(),_=function(){const e=Sf(e=>e.errors.updateAddressMethodId,e=>e.errors.updateAddressError,(e,t)=>n=>{if(!n||e===n)return t}),t=Sf(e=>e.errors.selectOptionMethodId,e=>e.errors.selectOptionError,(e,t)=>n=>{if(!n||e===n)return t}),n=Sf(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>n=>{if(!n||e===n)return t}),i=Sf(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>n=>{if(!n||e===n)return t}),r=Sf(e=>e.statuses.updateAddressMethodId,e=>e.statuses.isUpdatingAddress,(e,t)=>n=>!(n&&e!==n||!t)),o=Sf(e=>e.statuses.selectOptionMethodId,e=>e.statuses.isSelectingOption,(e,t)=>n=>!(n&&e!==n||!t)),a=Sf(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>n=>!(n&&e!==n||!t)),s=Sf(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),d=Sf(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>n=>!(n&&e!==n||!t));return Oe((c=U_)=>({getUpdateAddressError:e(c),getSelectOptionError:t(c),getInitializeError:n(c),getWidgetInteractionError:i(c),isUpdatingAddress:r(c),isSelectingOption:o(c),isInitializing:a(c),isInitialized:s(c),isWidgetInteracting:d(c)}))}(),S=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingConsignments))),n=Sf(e=>e.data,e=>t=>{if(e&&e.length)return j(e,{id:t})}),i=Sf(e=>e.data,e=>t=>{if(e&&e.length)return j(e,e=>{return n=e.shippingAddress,i=t,Y(pS(n),pS(i));var n,i})}),r=Sf(e=>e.data,e=>()=>{if(e&&e.length)return e[0].selectedShippingOption}),o=Sf(e=>e.errors.loadError,e=>()=>e),a=Sf(e=>e.errors.createError,e=>()=>e),s=Sf(e=>e.errors.loadShippingOptionsError,e=>()=>e),d=Sf(e,(e,{cart:t})=>t.getCart,(e,t)=>()=>{const n=t();if(!n)return[];const i=(e()||[]).reduce((e,t)=>e.concat(t.lineItemIds),[]);return(n.lineItems.physicalItems||[]).filter(e=>i.indexOf(e.id)<0)}),c=Sf(e=>e.errors.updateError,e=>t=>t?e[t]:j(e)),l=Sf(e=>e.errors.deleteError,e=>t=>t?e[t]:j(e)),u=Sf(i,c,a,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),h=Sf(e=>e.errors.updateShippingOptionError,e=>t=>t?e[t]:j(e)),p=Sf(e=>e.statuses.isLoading,e=>()=>!0===e),m=Sf(e=>e.statuses.isLoadingShippingOptions,e=>()=>!0===e),y=Sf(e=>e.statuses.isCreating,e=>()=>!0===e),g=Sf(e=>e.statuses.isUpdating,e=>t=>t?!0===e[t]:!0===j(e)),f=Sf(e=>e.statuses.isDeleting,e=>t=>t?!0===e[t]:!0===j(e)),v=Sf(i,g,y,(e,t,n)=>i=>{const r=e(i);return r?t(r.id):n()}),_=Sf(e=>e.statuses.isUpdatingShippingOption,e=>t=>t?!0===e[t]:!0===j(e));return Oe((S=b_,I)=>({getConsignments:e(S),getConsignmentsOrThrow:t(S),getConsignmentById:n(S),getConsignmentByAddress:i(S),getShippingOption:r(S),getLoadError:o(S),getCreateError:a(S),getLoadShippingOptionsError:s(S),getUnassignedItems:d(S,{cart:I}),getUpdateError:c(S),getDeleteError:l(S),getItemAssignmentError:u(S),getUpdateShippingOptionError:h(S),isLoading:p(S),isLoadingShippingOptions:m(S),isCreating:y(S),isUpdating:g(S),isDeleting:f(S),isAssigningItems:v(S),isUpdatingShippingOption:_(S)}))}(),I=function(){const e=Sf(e=>e.data,(e,{billingAddress:t})=>t.getBillingAddress,(e,{cart:t})=>t.getCart,(e,{customer:t})=>t.getCustomer,(e,{consignments:t})=>t.getConsignments,(e,{coupons:t})=>t.getCoupons,(e,{giftCertificates:t})=>t.getGiftCertificates,(e,t,n,i,r,o,a)=>()=>{const s=t(),d=n(),c=i(),l=r()||[],u=o()||[],h=a()||[];if(e&&d&&c)return Object.assign(Object.assign({},e),{billingAddress:s,cart:d,customer:c,consignments:l,coupons:u,giftCertificates:h})}),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingCheckout))),n=Sf(e,e=>t=>{const n=e();if(!n)return;const i=n.grandTotal||0,r=n.customer.storeCredit||0;return t?Math.max(i-r,0):n.outstandingBalance}),i=Sf(e=>e.errors.loadError,e=>()=>e),r=Sf(e=>e.errors.updateError,e=>()=>e),o=Sf(e=>e.statuses.isExecutingSpamCheck,e=>()=>!0===e),a=Sf(e=>e.statuses.isLoading,e=>()=>!0===e),s=Sf(e=>e.statuses.isUpdating,e=>()=>!0===e);return Oe((d=oS,c,l,u,h,p,m)=>({getCheckout:e(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getCheckoutOrThrow:t(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getOutstandingBalance:n(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getLoadError:i(d),getUpdateError:r(d),isExecutingSpamCheck:o(d),isLoading:a(d),isUpdating:s(d)}))}(),w=function(){const e=Sf(e=>e.data,(e,{billingAddress:t})=>t.getOrderBillingAddress(),(e,{coupons:t})=>t.getCoupons(),(e,t,n=[])=>()=>{if(e&&t)return Object.assign(Object.assign({},e),{billingAddress:t,coupons:n})}),t=Sf(e,e=>()=>lS(e(),()=>new ot(tt.MissingOrder))),n=Sf(e=>e.meta,e=>()=>e),i=Sf(e=>e.errors.loadError,e=>()=>e),r=Sf(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.payments},(e=[])=>t=>{const n=e.find(({providerId:e})=>e===t);return null==n?void 0:n.paymentId}),o=Sf(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((a=Gv,s,d)=>({getOrder:e(a,{billingAddress:s,coupons:d}),getOrderOrThrow:t(a,{billingAddress:s,coupons:d}),getOrderMeta:n(a),getLoadError:i(a),getPaymentId:r(a),isLoading:o(a)}))}(),C=function(){const e=Sf(e=>e.data,e=>()=>e);return Oe((t=Jv)=>({getOrderBillingAddress:e(t)}))}(),b=function(){const e=Sf(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.payment}),t=Sf(({order:e})=>e.getOrder,e=>()=>{const t=e();return j(t&&t.payments,({providerId:e})=>"giftcertificate"!==e&&"storecredit"!==e)}),n=Sf(({checkout:e})=>e.getCheckout,e=>()=>{const t=e();return j(t&&t.payments,({providerType:e})=>"PAYMENT_TYPE_HOSTED"===e)}),i=Sf(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.id)return{providerId:i.id,gatewayId:i.gateway};const r=t()||n();return r&&r.providerId?{providerId:r.providerId,gatewayId:r.gatewayId}:void 0}),r=Sf(i,e=>()=>lS(e(),()=>new ot(tt.MissingPaymentId))),o=Sf(e,n,t,(e,t,n)=>()=>{const i=e();if(i&&i.status)return i.status.replace("PAYMENT_STATUS_","");const r=t()||n();return r?r.detail.step:void 0}),a=Sf(o,e=>()=>lS(e(),()=>new ot(tt.MissingPaymentStatus))),s=Sf(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.token}),d=Sf(s,e=>()=>lS(e(),()=>new ot(tt.MissingPaymentToken))),c=Sf(e,e=>()=>{const t=e();return t&&t.redirectUrl}),l=Sf(c,e=>()=>lS(e(),()=>new ot(tt.MissingPaymentRedirectUrl))),u=Sf(({checkout:e})=>e.getOutstandingBalance,e=>(t=!1)=>{const n=e(t);return!!n&&n>0}),h=Sf(o,e=>t=>!(!t||!t.nonce)||"ACKNOWLEDGE"===e()||e()===$y);return Oe((e,t)=>({getPaymentId:i({checkout:e,order:t}),getPaymentIdOrThrow:r({checkout:e,order:t}),getPaymentStatus:o({checkout:e,order:t}),getPaymentStatusOrThrow:a({checkout:e,order:t}),getPaymentToken:s({checkout:e,order:t}),getPaymentTokenOrThrow:d({checkout:e,order:t}),getPaymentRedirectUrl:c({checkout:e,order:t}),getPaymentRedirectUrlOrThrow:l({checkout:e,order:t}),isPaymentDataRequired:u({checkout:e,order:t}),isPaymentDataSubmitted:h({checkout:e,order:t})}))}(),P=function(){const e=Sf(e=>e.errors.applyError,e=>()=>e),t=Sf(e=>!!e.statuses.isApplying,e=>()=>e);return Oe((n=mS)=>({getApplyError:e(n),isApplying:t(n)}))}(),O=function(){const e=Sf(e=>e.errors.updateError,e=>()=>e),t=Sf(e=>!!e.statuses.isUpdating,e=>()=>e);return Oe((n=tS)=>({getUpdateError:e(n),isUpdating:t(n)}))}(),E=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.errors.sendError,e=>()=>e),n=Sf(e=>!!e.statuses.isSending,e=>()=>e);return Oe((i=W_)=>({getEmail:e(i),getSendError:t(i),isSending:n(i)}))}(),A=function(){const e=Sf(e=>e.data,e=>()=>e),t=Sf(e=>e.data,e=>t=>null==e?void 0:e.find(e=>e.region===t)),n=Sf(e=>e.errors.loadError,e=>()=>e),i=Sf(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((r=Av)=>({getExtensions:e(r),getExtensionByRegion:t(r),getLoadError:n(r),isLoading:i(r)}))}();return(T,k={})=>{const D=e(T.b2bToken),M=t(T.billingAddress),z=n(T.cart),x=i(T.checkoutButton),N=o(T.countries),R=a(T.coupons),F=s(T.customer),L=d(T.customerStrategies),j=A(T.extensions),B=u(T.formFields),U=c(T.giftCertificates),q=l(T.instruments),V=C(T.orderBillingAddress),G=h(T.paymentMethods),H=y(T.paymentProviderCustomer),W=p(T.paymentStrategies),$=m(T.pickupOptions),Y=g(T.remoteCheckout),K=f(T.consignments),J=v(T.shippingCountries),Z=_(T.shippingStrategies),Q=O(T.subscriptions),X=P(T.storeCredit),ee=E(T.signInEmail),te=S(T.consignments,z),ne=I(T.checkout,M,z,te,R,F,U),ie=w(T.order,V,R),re=b(ne,ie),oe={b2bToken:D,billingAddress:M,cart:z,checkout:ne,checkoutButton:x,config:r(T.config,T.formFields),consignments:te,countries:N,coupons:R,customer:F,customerStrategies:L,extensions:j,form:B,giftCertificates:U,instruments:q,order:ie,orderBillingAddress:V,payment:re,paymentMethods:G,paymentProviderCustomer:H,paymentStrategies:W,pickupOptions:$,remoteCheckout:Y,shippingAddress:K,shippingCountries:J,shippingStrategies:Z,signInEmail:ee,subscriptions:Q,storeCredit:X};return k.shouldWarnMutation?function(e){return Object.keys(e).reduce((t,n)=>(t[n]=uS(e[n]),t),{})}(oe):oe}}function gS(e={},t){const n=(o=function(){const e=new Pf;return["catalog_only","empty_cart","invalid_order_id","invalid_order_token","missing_order_token","missing_provider_token","missing_shipping_method","order_completion_error","order_could_not_be_finalized_error","order_create_failed","provider_fatal_error","provider_setup_error","stock_too_low"].forEach(t=>{e.register(t,(e,t)=>new wf(e,t))}),e.register("invalid_payment_provider",e=>new Xr(e)),e.register("payment_config_not_found",e=>new Xr(e)),e}(),e=>_(e).pipe(P(e=>{if(e instanceof Error||e.payload instanceof Error)throw e;if((t=e.payload)&&"object"==typeof t&&["body","headers","status","statusText"].every(e=>Object.prototype.hasOwnProperty.call(t,e))){const t=e.payload.body&&e.payload.body.detail;throw Object.assign(Object.assign({},e),{payload:o.createError(e.payload,t)})}var t;throw e}))),i=yS(),r=d({b2bToken:Df,billingAddress:Ff,cart:Gf,checkout:aS,checkoutButton:Xf,config:rv,consignments:P_,countries:Bv,coupons:cv,customer:_v,customerStrategies:bv,extensions:Tv,formFields:xv,giftCertificates:mv,instruments:g_,orderBillingAddress:Zv,order:Hv,payment:Xv,paymentMethods:n_,paymentStrategies:d_,pickupOptions:M_,paymentProviderCustomer:p_,remoteCheckout:w_,shippingCountries:F_,shippingStrategies:q_,signInEmail:$_,subscriptions:nS,storeCredit:Q_});var o;return u(r,e,Object.assign({actionTransformer:n,stateTransformer:e=>i(e)},t))}function fS(e){var t;"https:"!==document.location.protocol&&wt().warn("The BigCommerce Checkout SDK should not be used on a non-HTTPS page");const i=null!==(t=null==e?void 0:e.rollOutLazyPaymentStrategies)&&void 0!==t&&t;"production"!==vt()&&wt().warn("Note that the development build is not optimized. To create a production build, set process.env.NODE_ENV to `production`.");const r={meta:{externalSource:e&&e.externalSource,host:null==e?void 0:e.host,locale:null==e?void 0:e.locale,variantIdentificationToken:window.checkoutVariantIdentificationToken},errors:{},statuses:{}},{locale:s="",shouldWarnMutation:d=!0}=e||{},c=n({host:e&&e.host}),l=gS({config:r},{shouldWarnMutation:d}),u=new ft(c,{getBasePath:()=>{var e,t;return null!==(t=null===(e=l.getState().config.getStoreConfig())||void 0===e?void 0:e.links.baseUrl)&&void 0!==t?t:void 0},getFeatures:()=>{var e,t,n;return null!==(n=null===(t=null===(e=l.getState().config.getStoreConfig())||void 0===e?void 0:e.checkoutSettings)||void 0===t?void 0:t.features)&&void 0!==n?n:{}}}),h=Gm(l),p=new Bm(u),m=new tn(u),y=new Pt(new kt(c)),g=Sn(o()),f=new In(u),v=new mn(g,f),_=new Vm(p,new ny(m)),S=new Rg(new Fg(u)),I=new an(new sn(u)),w=new rn(m,y,I),C=$g(l,u),b=function(e,t,n={useFallback:!1}){const{useFallback:i}=n,r=new Ht(i);for(const[,n]of Object.entries(t))if(qt(n))for(const t of n.resolveIds)r.register(t,()=>n(e));return r}(C,i?{createNoPaymentStrategy:Pd}:He,{useFallback:!0}),P=function(e,t){const n=new Ht;for(const[,i]of Object.entries(t))if(qt(i))for(const t of i.resolveIds)n.register(t,()=>i(e));return n}(C,i?{}:Ge),O=new Rn(new Fn(u)),E=new Wn,A=new Jn(l,E),T=yt(l,function(){const e=function(){const e=Sf(({checkout:e})=>e.getCheckout,e=>Ug(e)),t=Sf(({order:e})=>e.getOrder,e=>Ug(e)),n=Sf(({config:e})=>e.getStoreConfig,e=>Ug(e)),i=Sf(({shippingAddress:e})=>e.getShippingAddress,({config:e})=>e.getContextConfig,(e,t)=>Ug(()=>{const n=e(),i=t();if(!n){if(!i||!i.geoCountryCode)return;return{firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}}return n})),r=Sf(({consignments:e})=>e.getConsignments,e=>Ug(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.availableShippingOptions})),o=Sf(({consignments:e})=>e.getConsignments,e=>Ug(e)),a=Sf(({consignments:e})=>e.getConsignments,e=>Ug(()=>{const t=e(),n=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==n?void 0:n.selectedShippingOption})),s=Sf(({shippingCountries:e})=>e.getShippingCountries,e=>Ug(e)),d=Sf(({billingAddress:e})=>e.getBillingAddress,({config:e})=>e.getContextConfig,(e,t)=>Ug(()=>{const n=e(),i=t();return(!n||Ce(le(n,"shouldSaveAddress","email","id")).every(e=>!e||!e.length))&&i&&i.geoCountryCode?{id:n?n.id:"",firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",email:n?n.email:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:i.geoCountryCode}:n})),c=Sf(({countries:e})=>e.getCountries,e=>Ug(e)),l=Sf(({paymentMethods:e})=>e.getPaymentMethods,e=>Ug(e)),u=Sf(({paymentMethods:e})=>e.getPaymentMethod,e=>Ug(e)),h=Sf(({payment:e})=>e.getPaymentId,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Ug(()=>{const n=e();return n&&t(n.providerId,n.gatewayId)})),p=Sf(({cart:e})=>e.getCart,e=>Ug(e)),m=Sf(({coupons:e})=>e.getCoupons,e=>Ug(e)),y=Sf(({giftCertificates:e})=>e.getGiftCertificates,e=>Ug(e)),g=Sf(({customer:e})=>e.getCustomer,e=>Ug(e)),f=Sf(({signInEmail:e})=>e.getEmail,e=>Ug(e)),v=Sf(({b2bToken:e})=>e.getToken,e=>Ug(e)),_=Sf(({payment:e})=>e.isPaymentDataRequired,e=>Ug(e)),S=Sf(({payment:e})=>e.isPaymentDataSubmitted,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Ug((n,i)=>e(t(n,i)))),I=Sf(({instruments:e})=>e.getInstruments,({instruments:e})=>e.getInstrumentsByPaymentMethod,(e,t)=>Ug(function(n){return n?t(n):e()})),w=Sf(({form:e})=>e.getCustomerAccountFields,e=>Ug(e)),C=Sf(({form:e})=>e.getBillingAddressFields,({countries:e})=>e.getCountries,(e,t)=>Ug(n=>e(t(),n))),b=Sf(({form:e})=>e.getShippingAddressFields,({shippingCountries:e})=>e.getShippingCountries,(e,t)=>Ug(n=>e(t(),n))),P=Sf(({form:e})=>e.getAddressExtraFields,e=>Ug(e)),O=Sf(({config:e})=>e.getFlashMessages,e=>Ug(e)),E=Sf(({pickupOptions:e})=>e.getPickupOptions,e=>Ug(e)),A=Sf(({config:e})=>e.getStoreConfig,e=>Ug(()=>{const t=e();if(t)return t.checkoutSettings.checkoutUserExperienceSettings})),T=Sf(({extensions:e})=>e.getExtensions,e=>Ug(e)),k=Sf(({paymentProviderCustomer:e})=>e.getPaymentProviderCustomer,e=>Ug(e)),D=Sf(({extensions:e})=>e.getExtensionByRegion,e=>Ug(e));return Oe(M=>({getCheckout:e(M),getOrder:t(M),getConfig:n(M),getExtensions:T(M),getExtensionByRegion:D(M),getFlashMessages:O(M),getShippingAddress:i(M),getShippingOptions:r(M),getConsignments:o(M),getSelectedShippingOption:a(M),getShippingCountries:s(M),getBillingAddress:d(M),getBillingCountries:c(M),getPaymentMethods:l(M),getPaymentMethod:u(M),getSelectedPaymentMethod:h(M),getCart:p(M),getCoupons:m(M),getGiftCertificates:y(M),getCustomer:g(M),isPaymentDataRequired:_(M),isPaymentDataSubmitted:S(M),getSignInEmail:f(M),getB2BToken:v(M),getInstruments:I(M),getCustomerAccountFields:w(M),getBillingAddressFields:C(M),getShippingAddressFields:b(M),getAddressExtraFields:P(M),getPickupOptions:E(M),getUserExperienceSettings:A(M),getPaymentProviderCustomer:k(M)}))}(),t=function(){const e=If(e=>e,e=>()=>{for(const t of Object.keys(e)){const n=e[t]();if(n)return n}}),t=Sf(({shippingStrategies:e})=>e.getSelectOptionError,({consignments:e})=>e.getUpdateShippingOptionError,(e,t)=>n=>e()||t(n));return Oe(n=>{const i={getLoadCheckoutError:n.checkout.getLoadError,getUpdateCheckoutError:n.checkout.getUpdateError,getSubmitOrderError:n.paymentStrategies.getExecuteError,getFinalizeOrderError:n.paymentStrategies.getFinalizeError,getLoadOrderError:n.order.getLoadError,getLoadCartError:n.cart.getLoadError,getLoadBillingCountriesError:n.countries.getLoadError,getLoadShippingCountriesError:n.shippingCountries.getLoadError,getLoadPaymentMethodsError:n.paymentMethods.getLoadError,getLoadPaymentMethodError:n.paymentMethods.getLoadMethodError,getInitializePaymentError:n.paymentStrategies.getInitializeError,getSignInError:n.customerStrategies.getSignInError,getSignOutError:n.customerStrategies.getSignOutError,getInitializeCustomerError:n.customerStrategies.getInitializeError,getLoadShippingOptionsError:n.consignments.getLoadShippingOptionsError,getSelectShippingOptionError:t(n),getContinueAsGuestError:n.billingAddress.getContinueAsGuestError,getUpdateBillingAddressError:n.billingAddress.getUpdateError,getUpdateSubscriptionsError:n.subscriptions.getUpdateError,getUpdateShippingAddressError:n.shippingStrategies.getUpdateAddressError,getDeleteConsignmentError:n.consignments.getDeleteError,getUpdateConsignmentError:n.consignments.getUpdateError,getCreateConsignmentsError:n.consignments.getCreateError,getInitializeShippingError:n.shippingStrategies.getInitializeError,getApplyStoreCreditError:n.storeCredit.getApplyError,getApplyCouponError:n.coupons.getApplyError,getRemoveCouponError:n.coupons.getRemoveError,getApplyGiftCertificateError:n.giftCertificates.getApplyError,getRemoveGiftCertificateError:n.giftCertificates.getRemoveError,getLoadInstrumentsError:n.instruments.getLoadError,getDeleteInstrumentError:n.instruments.getDeleteError,getLoadConfigError:n.config.getLoadError,getSignInEmailError:n.signInEmail.getSendError,getLoadB2BTokenError:n.b2bToken.getLoadError,getCreateCustomerAccountError:n.customer.getCreateAccountError,getCreateCustomerAddressError:n.customer.getCreateAddressError,getPickupOptionsError:n.pickupOptions.getLoadError,getLoadExtensionsError:n.extensions.getLoadError};return Object.assign({getError:e(i)},i)})}(),n=function(){const e=If(e=>e,e=>()=>Object.keys(e).some(t=>e[t]())),t=Sf(({shippingStrategies:e})=>e.isSelectingOption,({consignments:e})=>e.isUpdatingShippingOption,(e,t)=>n=>e()||t(n)),n=Sf(({customerStrategies:e})=>e.isInitializing,({customerStrategies:e})=>e.isSigningIn,({customerStrategies:e})=>e.isSigningOut,({customerStrategies:e})=>e.isExecutingPaymentMethodCheckout,({customerStrategies:e})=>e.isWidgetInteracting,(e,t,n,i,r)=>o=>e(o)||t(o)||n(o)||i(o)||r(o)),i=Sf(({shippingStrategies:e})=>e.isInitializing,({shippingStrategies:e})=>e.isUpdatingAddress,({shippingStrategies:e})=>e.isSelectingOption,({shippingStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),r=Sf(({paymentStrategies:e})=>e.isInitializing,({paymentStrategies:e})=>e.isExecuting,({paymentStrategies:e})=>e.isFinalizing,({paymentStrategies:e})=>e.isWidgetInteracting,(e,t,n,i)=>r=>e(r)||t(r)||n(r)||i(r)),o=Sf(({paymentStrategies:e})=>e.isExecuting,({checkout:e})=>e.isExecutingSpamCheck,(e,t)=>n=>e(n)||t());return Oe(a=>{const s={isLoadingCheckout:a.checkout.isLoading,isUpdatingCheckout:a.checkout.isUpdating,isExecutingSpamCheck:a.checkout.isExecutingSpamCheck,isSubmittingOrder:o(a),isFinalizingOrder:a.paymentStrategies.isFinalizing,isLoadingOrder:a.order.isLoading,isLoadingCart:a.cart.isLoading,isLoadingBillingCountries:a.countries.isLoading,isLoadingShippingCountries:a.shippingCountries.isLoading,isLoadingPaymentMethods:a.paymentMethods.isLoading,isLoadingPaymentMethod:a.paymentMethods.isLoadingMethod,isInitializingPayment:a.paymentStrategies.isInitializing,isSigningIn:a.customerStrategies.isSigningIn,isSigningOut:a.customerStrategies.isSigningOut,isExecutingPaymentMethodCheckout:a.customerStrategies.isExecutingPaymentMethodCheckout,isInitializingCustomer:a.customerStrategies.isInitializing,isInitializedCustomer:a.customerStrategies.isInitialized,isLoadingShippingOptions:a.consignments.isLoadingShippingOptions,isSelectingShippingOption:t(a),isUpdatingBillingAddress:a.billingAddress.isUpdating,isUpdatingSubscriptions:a.subscriptions.isUpdating,isCreatingCustomerAccount:a.customer.isCreatingCustomerAccount,isCreatingCustomerAddress:a.customer.isCreatingCustomerAddress,isContinuingAsGuest:a.billingAddress.isContinuingAsGuest,isUpdatingShippingAddress:a.shippingStrategies.isUpdatingAddress,isUpdatingConsignment:a.consignments.isUpdating,isDeletingConsignment:a.consignments.isDeleting,isCreatingConsignments:a.consignments.isCreating,isInitializingShipping:a.shippingStrategies.isInitializing,isApplyingStoreCredit:a.storeCredit.isApplying,isApplyingCoupon:a.coupons.isApplying,isRemovingCoupon:a.coupons.isRemoving,isApplyingGiftCertificate:a.giftCertificates.isApplying,isRemovingGiftCertificate:a.giftCertificates.isRemoving,isLoadingInstruments:a.instruments.isLoading,isDeletingInstrument:a.instruments.isDeleting,isLoadingConfig:a.config.isLoading,isSendingSignInEmail:a.signInEmail.isSending,isLoadingB2BToken:a.b2bToken.isLoading,isCustomerStepPending:n(a),isShippingStepPending:i(a),isPaymentStepPending:r(a),isLoadingPickupOptions:a.pickupOptions.isLoading};return Object.assign({isPending:e(s)},s)})}();return i=>({data:e(i),errors:t(i),statuses:n(i)})}());return new vf(l,T,A,function(e,t){const n={[Yn.ConsignmentsChanged]:Qn};return new Zn(e,t,n)}(T,A),new Xe(new it(c)),new dt(new ht(u),S),w,y,new Jt(new Zt(u),w,v),new Pg(new Eg(u),m),new zm(new xm(u,{locale:s})),new Mt(new jt(u)),new Xt(function(e,t){const n=new Gt,i=a(),r=new tn(t),o=new rn(r,new Pt(new kt(t)),new an(new sn(t))),s=new mn(Sn(i),new In(t)),d=new Jt(new Zt(t),o,s);return n.register("default",()=>new wn(e,d)),n}(l,u),P,C),new gt,new Bt(new Ut(u)),new Yg(new Xg(h,u)),_,new Wm(new $m(u)),new Xm(function(e,t,n){const i=new Wy({defaultToken:Zm.CREDIT_CARD}),r=a(),s=new Gy,d=new by(t),c=new tn(n),l=new ny(c),u=new Vm(new Bm(n),l),h=new cy(Sn(o())),p=new Cy(d,u,s,h),m=Ee(),y=((e,t)=>new ig(new ng(e,t)))(m,h),g=new wy(e);return i.register(Zm.CONVERGE,()=>new Zy(e,u,p,g,m)),i.register(Zm.PPSDK,()=>new dg(e,u,((e,t,n,i,r)=>{const o=new lg;return o.register(ag.CARD,()=>new hg(e,t,r,i)),o.register(ag.NONE,()=>new pg(n,i)),o.register(ag.UNSUPPORTED,()=>{}),o})(e,u,n,y,g),new fg(n,y),new iy("PPSDK"))),i.register(Zm.WE_PAY,()=>new vg(e,u,p,g,new _g(r))),i}(l,h,u),b,_,v,C),new ef(new tf(u)),new kg(new Dg(u,{locale:s}),l),new nf(function(e,t){const n=new Gt,i=$g(e),r=new tn(t),o=new Eg(t),s=new Pg(o,r),d=new Wm(new $m(t)),c=a(),l=new Rg(new Fg(t)),u=new dt(new ht(t),l),h=window,p=new Ei(i);return n.register("amazonpay",()=>new af(e,s,new Wm(new $m(t)),gi(),new nf(n))),n.register("stripeupe",()=>new pf(e,new Ra(c),s,d)),n.register("braintreeacceleratedcheckout",()=>new df(e,u,s,d,new Ig,new So(new Hi(a(),h,p),h))),n.register("paypalcommerceacceleratedcheckout",()=>new uf(e,u,s,d,new Ig,Cs(),nd())),n.register("default",()=>new cf(e,s)),n}(l,u)),new mf(new yf(u)),v,new zg(new xg(u)),S,I,O,E)}const vS=e=>{const t=we(e);return document.getElementById(t)?vS(e):t};function _S(e){return Object.prototype.hasOwnProperty.call(e,"cacheKey")}class SS{constructor(e){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=Object.assign({maxSize:0,isEqual:je,onExpire:ce},e)}getKey(...e){const t=this._resolveMap(...e),{index:n,parentMap:i}=t;let{map:r}=t;return r&&r.cacheKey?r.usedCount++:r=this._generateMap(i,e.slice(n)),this._removeLeastUsedMap(r),r.cacheKey}getUsedCount(...e){const{map:t}=this._resolveMap(...e);return t?t.usedCount:0}_resolveMap(...e){let t=0,n=this._map;for(;n.maps.length;){let i=!1;for(let r=0;r<n.maps.length;r++){const o=n.maps[r];if(this._options.isEqual(o.value,e[t])){if(n.maps.unshift(...n.maps.splice(r,1)),(0===e.length||t===e.length-1)&&_S(o))return{index:t,map:o,parentMap:n};i=!0,n=o,t++;break}}if(!i)break}return{index:t,parentMap:n}}_generateMap(e,t){let n,i=0,r=e;do{n={maps:[],parentMap:r,usedCount:1,value:t[i]},r.maps.unshift(n),r=n,i++}while(i<t.length);const o=n;return o.cacheKey=""+ ++this._lastId,o}_removeLeastUsedMap(e){if(!this._options.maxSize)return;const t=this._usedMaps.indexOf(e);if(this._usedMaps.splice(-1===t?0:t,-1===t?0:1,e),this._usedMaps.length<=this._options.maxSize)return;const n=this._usedMaps.pop();n&&(this._removeMap(n),this._options.onExpire(n.cacheKey))}_removeMap(e){e.parentMap&&(e.parentMap.maps.splice(e.parentMap.maps.indexOf(e),1),function(e){return Object.prototype.hasOwnProperty.call(e,"parentMap")}(e.parentMap)||this._removeMap(e.parentMap))}}function IS(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(n=>{const i=Object.getOwnPropertyDescriptor(e.prototype,n);i&&"constructor"!==n&&Object.defineProperty(t.prototype,n,function(e,t,n){if("function"!=typeof n.value)return n;let i=new SS,r=n.value,o=Pe(r);return Ln(e,t,{get(){const e=(...e)=>{const t=o.call(this,...e);if(1===i.getUsedCount(...e))return t;const n=r.call(this,...e);return Af(n,t,{keyFilter:e=>!function(e){return 0===`${e}`.indexOf("$$")||0===`${e}`.indexOf("_")}(e)})?t:(o.cache.set(i.getKey(...e),n),n)};return Object.defineProperty(this,t,Object.assign(Object.assign({},n),{value:e})),e},set(e){i=new SS,r=e,o=Pe(r)}})}(e.prototype,n,i))}),t}let wS=class{constructor(e){this._checkoutButton=e.checkoutButton}getInitializeButtonError(e){return this._checkoutButton.getInitializeError(e)}getDeinitializeButtonError(e){return this._checkoutButton.getDeinitializeError(e)}};wS=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([IS],wS);const CS=wS;let bS=class{constructor(e){this._checkoutButton=e.checkoutButton}isInitializingButton(e){return this._checkoutButton.isInitializing(e)}isDeinitializingButton(e){return this._checkoutButton.isDeinitializing(e)}};bS=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([IS],bS);const PS=bS;function OS(e){return{errors:new CS(e),statuses:new PS(e)}}let ES=class{constructor(e,t){this._store=e,this._buttonStrategyActionCreator=t,this._state=OS(this._store.getState()),this._store.subscribe(e=>{this._state=OS(e)})}getState(){return this._state}subscribe(e,...t){return this._store.subscribe(()=>e(this.getState()),e=>e.checkoutButton.getState(),...t.map(e=>t=>e(OS(t))))}initializeButton(e){const t=(n=e.containerId,/^\w[\w\-\:\.]*$/.test(n)?[e.containerId]:function(e,t){const n=document.querySelectorAll(e);if(!n.length)throw new Vt(`Unable to find any element with the specified selector: ${e}`);return Array.prototype.slice.call(n).map(e=>(e.id||(e.id=vS(t)),e.id))}(e.containerId,`${e.methodId}-container`));var n;return Promise.all(t.map(t=>{const n=this._buttonStrategyActionCreator.initialize(Object.assign(Object.assign({},e),{containerId:t})),i=`checkoutButtonStrategy:${e.methodId}:${t}`;return this._store.dispatch(n,{queueId:i})})).then(()=>this.getState())}deinitializeButton(e){const t=this._buttonStrategyActionCreator.deinitialize(e),n=`checkoutButtonStrategy:${e.methodId}`;return this._store.dispatch(t,{queueId:n}).then(()=>this.getState())}};ES=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],ES);const AS=ES;class TS{constructor(e,t,n){this._registry=e,this._registryV2=t,this._paymentMethodActionCreator=n}initialize(e){return t=>{const n={methodId:e.methodId,containerId:e.containerId};if(t.getState().checkoutButton.isInitialized(e.methodId,e.containerId))return v();const i=e.currencyCode?{params:{currencyCode:e.currencyCode}}:{},r=Object.assign(Object.assign({},i),{timeout:e.timeout,useCache:!0});return g(C(l(Yf.InitializeButtonRequested,void 0,n)),this._paymentMethodActionCreator.loadPaymentMethod(e.methodId,r)(t),f(()=>this._getStrategy(e.methodId).initialize(e).then(()=>l(Yf.InitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Ke(Yf.InitializeButtonFailed,e,n)))}}deinitialize(e){return t=>{const n={methodId:e.methodId};return t.getState().checkoutButton.isInitialized(e.methodId)?g(C(l(Yf.DeinitializeButtonRequested,void 0,n)),f(()=>this._getStrategy(e.methodId).deinitialize().then(()=>l(Yf.DeinitializeButtonSucceeded,void 0,n)))).pipe(P(e=>Ke(Yf.DeinitializeButtonFailed,e,n))):v()}}_getStrategy(e){let t;try{t=this._registryV2.get({id:e})}catch(n){t=this._registry.get(e)}return t}}class kS extends rt{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"}}var DS,MS,zS,xS,NS,RS,FS,LS;class jS{constructor(e){this._scriptLoader=e,this._window=window}loadPaypal(e=""){return t=this,n=void 0,r=function*(){const t="//www.paypalobjects.com/api/checkout.min.js",n={async:!0,attributes:{"data-merchant-id":e}};if(e?yield this._scriptLoader.loadScript(t,n):yield this._scriptLoader.loadScript(t),!this._window.paypal)throw new kS;return this._window.paypal},new((i=void 0)||(i=Promise))(function(e,o){function a(e){try{d(r.next(e))}catch(e){o(e)}}function s(e){try{d(r.throw(e))}catch(e){o(e)}}function d(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(e){e(n)})).then(a,s)}d((r=r.apply(t,n||[])).next())});var t,n,i,r}}!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(DS||(DS={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(MS||(MS={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(zS||(zS={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(xS||(xS={})),function(e){e.PILL="pill",e.RECT="rect"}(NS||(NS={}));class BS{constructor(e,t,n,i,r=""){this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=n,this._formPoster=i,this._host=r}initialize(e){const t=e.paypal,n=this._store.getState(),i=this._paymentMethod=n.paymentMethods.getPaymentMethod(e.methodId);if(!t)throw new Vt;if(!i)throw new ot(tt.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then(n=>{var r,o;if(!i||!i.config.merchantId)throw new ot(tt.MissingPaymentMethod);const a=i.config.merchantId,s=i.config.testMode?"sandbox":"production",d={[s]:t.clientId},c=n.FUNDING.CREDIT||"credit",l=t.allowCredit?[c]:[],u=t.allowCredit?[]:[c];return n.Button.render({env:s,client:d,commit:t.shouldProcessPayment,funding:{allowed:l,disallowed:u},style:Object.assign(Object.assign({shape:NS.RECT},pe(t.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(r=t.style)||void 0===r?void 0:r.size)?MS.RESPONSIVE:null===(o=t.style)||void 0===o?void 0:o.size}),payment:(e,n)=>this._setupPayment(a,n,t.onPaymentError),onAuthorize:(e,n)=>this._tokenizePayment(e,n,t.shouldProcessPayment,t.onAuthorizeError)},e.containerId)})}deinitialize(){return this._paymentMethod=void 0,Promise.resolve()}_setupPayment(e,t,n){if(!t)throw new gn(ln.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then(n=>{const i=n.cart.getCart(),r=i?i.id:"";return t.request.post(`${this._host}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:r},{headers:Object.assign({"X-API-INTERNAL":Tt},et)})}).then(e=>e.id).catch(e=>{throw n&&n(e),e})}_tokenizePayment(e,t,n,i){if(!this._paymentMethod)throw new gn(ln.CheckoutButtonNotInitialized);if(!t)throw new gn(ln.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new ot(tt.MissingPayment);const r=this._paymentMethod.id;return t.payment.get(e.paymentID).then(t=>{this._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})})}}function US(e){const{host:t}=null!=e?e:{},i=gS({config:{meta:{host:null==e?void 0:e.host,locale:null==e?void 0:e.locale},errors:{},statuses:{}}}),r=n({host:t}),o=Ee({host:t}),s=function(e){const t=new Ht;for(const[,n]of Object.entries({}))if(qt(n))for(const i of n.resolveIds)t.register(i,()=>n(e));return t}($g(i));return new AS(i,new TS(function(e,t,n,i){const r=new Gt,o=a(),s=new tn(t),d=new rn(s,new Pt(new kt(t)),new an(new sn(t)));return r.register(zy.PAYPALEXPRESS,()=>new BS(e,d,new jS(o),n,i)),r}(i,r,o,t),s,new Wm(new $m(r))))}!function(e){e.CheckoutComplete="CHECKOUT_COMPLETE",e.CheckoutError="CHECKOUT_ERROR",e.CheckoutLoaded="CHECKOUT_LOADED",e.FrameError="FRAME_ERROR",e.FrameLoaded="FRAME_LOADED",e.SignedOut="SIGNED_OUT"}(RS||(RS={}));class qS extends Et{constructor(e){super(e,{message:e.body.title}),this.name="InvalidLoginTokenError",this.type="invalid_login_token"}}!function(e){e.MissingContainer="missing_container",e.MissingContent="missing_content",e.UnknownError="unknown_error"}(FS||(FS={}));class VS extends rt{constructor(e,t=FS.UnknownError){super(e||"Unable to embed the checkout form."),this.subtype=t,this.name="NotEmbeddableError",this.type="not_embeddable"}}!function(e){e.StyleConfigured="STYLE_CONFIGURED"}(LS||(LS={}));const GS="isCookieAllowed",HS="lastAllowCookieAttempt";let WS=class{constructor(e,t,n,i,r,o,a,s){this._iframeCreator=e,this._messageListener=t,this._messagePoster=n,this._loadingIndicator=i,this._requestSender=r,this._storage=o,this._location=a,this._options=s,this._isAttached=!1,this._options.onComplete&&this._messageListener.addListener(RS.CheckoutComplete,this._options.onComplete),this._options.onError&&this._messageListener.addListener(RS.CheckoutError,this._options.onError),this._options.onLoad&&this._messageListener.addListener(RS.CheckoutLoaded,this._options.onLoad),this._options.onFrameLoad&&this._messageListener.addListener(RS.FrameLoaded,this._options.onFrameLoad),this._options.onSignOut&&this._messageListener.addListener(RS.SignedOut,this._options.onSignOut),this._messageListener.addListener(RS.FrameLoaded,()=>this._configureStyles())}attach(){return this._isAttached?Promise.resolve(this):(this._isAttached=!0,this._messageListener.listen(),this._loadingIndicator.show(this._options.containerId),this._allowCookie().then(()=>this._attemptLogin()).then(e=>this._iframeCreator.createFrame(e,this._options.containerId)).then(e=>{this._iframe=e,this._configureStyles(),this._loadingIndicator.hide()}).catch(e=>(this._isAttached=!1,this._retryAllowCookie(e).catch(()=>{throw this._messageListener.trigger({type:RS.FrameError,payload:e}),this._loadingIndicator.hide(),e}))).then(()=>this))}detach(){this._isAttached&&(this._isAttached=!1,this._messageListener.stopListen(),this._iframe&&this._iframe.parentNode&&(this._iframe.parentNode.removeChild(this._iframe),this._iframe.iFrameResizer.close()))}_configureStyles(){this._iframe&&this._iframe.contentWindow&&this._options.styles&&(this._messagePoster.setTarget(this._iframe.contentWindow),this._messagePoster.post({type:LS.StyleConfigured,payload:this._options.styles}))}_attemptLogin(){return/^\/login\/token/.test(Cn(this._options.url).pathname)?this._requestSender.post(this._options.url).then(({body:{redirectUrl:e}})=>e).catch(e=>Promise.reject(new qS(e))):Promise.resolve(this._options.url)}_allowCookie(){if(this._storage.getItem(GS))return Promise.resolve();this._storage.setItem(GS,!0),this._storage.setItem(HS,Date.now());const{origin:e}=Cn(this._options.url),t=`${e}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(this._location.href)}`;return document.body.style.visibility="hidden",this._location.replace(t),new Promise(()=>{})}_retryAllowCookie(e){const t=Number(this._storage.getItem(HS));return(!t||Date.now()-t>6e5)&&e instanceof VS&&e.subtype===FS.MissingContent?(this._storage.removeItem(HS),this._storage.removeItem(GS),this._allowCookie()):Promise.reject()}};WS=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],WS);const $S=WS;class YS{constructor(e){this._options=e}createFrame(e,t){const n=document.getElementById(t),{timeout:i=6e4}=this._options||{};if(!n)throw new VS("Unable to embed the iframe because the container element could not be found.",FS.MissingContainer);const r=document.createElement("iframe");return r.src=e,r.style.border="none",r.style.display="none",r.style.width="100%",r.allowPaymentRequest=!0,r.allow="payment",n.appendChild(r),this._toResizableFrame(r,i).catch(e=>{throw n.removeChild(r),e})}_toResizableFrame(e,t){return new Promise((n,i)=>{const r=window.setTimeout(()=>{i(new VS("Unable to embed the iframe because the content could not be loaded."))},t),o=t=>{if((t.origin===Cn(e.src).origin||t.origin===$n(Cn(e.src)).origin)&&(Pn(t.data,RS.FrameError)&&(a(),i(new VS(t.data.payload.message,FS.MissingContent))),Pn(t.data,RS.FrameLoaded))){e.style.display="";const i=Mn({scrolling:!1,sizeWidth:!1,heightCalculationMethod:t.data.payload&&t.data.payload.contentId?"taggedElement":"lowestElement"},e);a(),n(i[i.length-1])}},a=()=>{window.removeEventListener("message",o),window.clearTimeout(r)};window.addEventListener("message",o)})}}function KS(e){const t=Cn(e.url).origin;return new $S(new YS,new Kn(t),new On(t),new fd({styles:e.styles&&e.styles.loadingIndicator}),n(),new iy("BigCommerce.EmbeddedCheckout"),window.location,e).attach()}function JS(e){if(!e.payload||!e.payload.contentId)return;const t=document.getElementById(e.payload.contentId);t&&!t.hasAttribute("data-iframe-height")&&t.setAttribute("data-iframe-height","")}function ZS(e){return"object"==typeof e&&null!==e&&"message"in e&&"type"in e}let QS=class{constructor(e,t,n,i={}){this._messageListener=e,this._messagePoster=t,this._untargetedMessagePoster=n,this._messageHandlers=i,this._messageListener.listen()}postComplete(){const e={type:RS.CheckoutComplete};this._postMessage(e)}postError(e){const t={type:RS.CheckoutError,payload:this._transformError(e)};this._postMessage(t)}postFrameError(e){const t={type:RS.FrameError,payload:this._transformError(e)};this._postMessage(t,{untargeted:!0})}postFrameLoaded(e){const t={type:RS.FrameLoaded,payload:e};this._postMessage(t)}postLoaded(){const e={type:RS.CheckoutLoaded};this._postMessage(e)}postSignedOut(){const e={type:RS.SignedOut};this._postMessage(e)}receiveStyles(e){this._messageListener.addListener(LS.StyleConfigured,({payload:t})=>{e(t)})}_postMessage(e,t){if(this._notifyMessageHandlers(e),t&&t.untargeted)return this._untargetedMessagePoster.post(e);this._messagePoster.post(e)}_notifyMessageHandlers(e){Object.keys(this._messageHandlers).forEach(t=>{if(e.type!==t)return;const n=this._messageHandlers[t];n&&n.call(null,e)})}_transformError(e){return{message:e.message,type:ZS(e)?e.type:void 0,subtype:ZS(e)?e.subtype:void 0}}};QS=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],QS);const XS=QS;let eI=class{postComplete(){}postError(){}postFrameError(){}postFrameLoaded(){}postLoaded(){}postSignedOut(){}receiveStyles(){}};eI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],eI);const tI=eI;function nI(e){Ve(939);const t=e.parentWindow||window.parent;return window===t?new tI:new XS(new Kn(e.parentOrigin),new On(e.parentOrigin,t),new On("*",t),{[RS.FrameLoaded]:JS})}const iI="en",rI="optimized_checkout";let oI=class{constructor(e,t){this._logger=t;const{locale:n,locales:i,translations:r}=this._transformConfig(e);this._locale=n,this._locales=i,this._translations=r,this._formatters={}}mapKeys(e){Object.keys(e).forEach(t=>{const n=`${rI}.${e[t]}`;this._translations[`${rI}.${t}`]=this._translations[n]})}getLocale(){return this._hasTranslations()?this._locale:iI}translate(e,t={}){var n;const i=`${rI}.${e}`;if("string"!=typeof this._translations[i])return this._logger.warn(`Translation key "${i}" is missing`),i;this._formatters[i]||(this._formatters[i]=new Be(this._escapeSpecialCharacters(this._translations[i]||""),this._locales[i],void 0,{ignoreTag:!0}));try{return this._formatters[i].format(this._transformData(t))}catch(e){if(this._isFormatError(e))return null!==(n=e.originalMessage)&&void 0!==n?n:"";throw e}}_transformConfig(e={}){const t={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:e.locale||iI},n=e.locales||{},i=this._flattenObject(e.translations||{}),r=this._flattenObject(e.defaultTranslations||{}),o=this._flattenObject(e.fallbackTranslations||{});return Se(Object.keys(o),Object.keys(r),Object.keys(i)).forEach(a=>{var s,d;i&&i[a]?(t.translations[a]=i[a],t.locales[a]=n[a]||t.locale):r[a]?(t.translations[a]=r[a],t.locales[a]=null!==(s=e.defaultLocale)&&void 0!==s?s:iI):(t.translations[a]=o[a],t.locales[a]=null!==(d=e.fallbackLocale)&&void 0!==d?d:iI)}),t}_flattenObject(e,t={},n=""){try{Object.keys(e).forEach(i=>{const r=e[i],o=n?`${n}.${i}`:i;if(Z(r))return this._flattenObject(r,t,o);t[o]=r})}catch(e){this._logger.warn(`Unable to parse object: ${e}`)}return t}_transformData(e){return Object.keys(e).reduce((t,n)=>{const i=e[n];return t[n]=null==i?"":i,t},{})}_hasTranslations(){return Object.keys(this._locales).map(e=>this._locales[e]).filter(e=>e.split("-")[0]===this._locale.split("-")[0]).length>0}_isFormatError(e){return"object"==typeof e&&null!==e&&"originalMessage"in e}_escapeSpecialCharacters(e){return e.replace(/(\w+)='([^']*)'/g,"$1=''$2''")}};oI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],oI);const aI=oI;function sI(e={}){return new aI(e,wt())}let dI=class{constructor(e){this._storeConfig=e,this._customerFormatter=new Fo(this._storeConfig.shopperCurrency),this._storeFormatter=new Fo(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};dI=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}([Ln],dI);const cI=dI;function lI(e){return new cI(e)}function uI(e){return e&&"ga"in e&&"function"==typeof e.ga}function hI(e,t){uI(window)&&window.ga("send",e,Object.assign(Object.assign({},t),{nonInteraction:!1}))}function pI(e){return mI(e).length>=8096}function mI(e){return Object.keys(e).reduce((t,n)=>{const i=typeof e[n];return"string"===i||"number"===i?[...t,`${n}=${e[n]}`]:"object"===i&&null!==e[n]?[...t,mI(e[n])]:t},[]).join("&")}var yI;!function(e){e[e.CUSTOMER=1]="CUSTOMER",e[e.SHIPPING=2]="SHIPPING",e[e.BILLING=3]="BILLING",e[e.PAYMENT=4]="PAYMENT"}(yI||(yI={}));const gI={customer:yI.CUSTOMER,shipping:yI.SHIPPING,billing:yI.BILLING,payment:yI.PAYMENT};class fI{constructor(e,t,n,{checkoutSteps:i}={}){if(this.checkoutService=e,this.analyticsExtraItemsManager=t,this.analytics=n,this._checkoutStarted=!1,this._completedSteps={},this._viewedSteps={},this._analyticStepOrder=["customer","shipping","billing","payment"],void 0!==i){if(i.some(e=>!(e in gI)))throw new Vt(`Invalid checkout steps provided. Valid values are: ${ie(gI).join(", ")}.`);this._analyticStepOrder=i}}trackCheckoutStarted(){if(this._checkoutStarted)return;const e=this.getCheckout();if(!e)return;const{coupons:t,grandTotal:n,shippingCostTotal:i,taxTotal:r,cart:{lineItems:o,discountAmount:a,id:s}}=e,d=this.analyticsExtraItemsManager.saveExtraItemsData(s,o);this.analytics.track("Checkout Started",this.getTrackingPayload({revenue:n,shipping:i,tax:r,discount:a,coupons:t,lineItems:o,extraItemsData:d})),this._checkoutStarted=!0}trackOrderComplete(){var e;const t=this.getOrder();if(!t)return;const{isComplete:n,orderId:i,orderAmount:r,shippingCostTotal:o,taxTotal:a,discountAmount:s,coupons:d,lineItems:c,cartId:l}=t;if(!n)return;const u=this.analyticsExtraItemsManager.readExtraItemsData(l);if(null===u)return;const h=null===(e=this.checkoutService.getState().data.getConfig())||void 0===e?void 0:e.checkoutSettings.features["DATA-6891.missing_orders_within_GA"],p=this.getTrackingPayload({orderId:i,revenue:r,shipping:o,tax:a,discount:s,coupons:d,extraItemsData:u,lineItems:c});if(h&&pl(window)&&uI(window)&&pI(p))return hI("transaction",{"&ti":p.order_id,"&ta":p.affiliation,"&tr":p.revenue,"&ts":p.shipping,"&tt":p.tax,"&tcc":p.coupon,"&cu":p.currency}),p.products.forEach(e=>{hI("item",{"&ti":p.order_id,"&in":e.name,"&ic":e.sku,"&iv":`${e.category}`,"&ip":e.price,"&iq":e.quantity})}),this.analyticsExtraItemsManager.clearExtraItemData(l);this.analytics.track("Order Completed",p),this.analyticsExtraItemsManager.clearExtraItemData(l)}trackStepViewed(e){const t=this.getIdFromStep(e);t&&!this.hasStepViewed(t)&&(this.trackViewed(t),this.backfill(t))}trackStepCompleted(e){const t=this.getIdFromStep(e);t&&!this.hasStepCompleted(t)&&(this.backfill(t),this.trackCompleted(t))}backfill(e){for(const t of this._analyticStepOrder){const n=this.getIdFromStep(t);if(!n)break;if(this.hasStepViewed(n)||this.trackViewed(n),n===e)break;this.hasStepCompleted(n)||this.trackCompleted(n)}}trackCompleted(e){const t=this.getSelectedShippingOption(),{code:n=""}=this.getShopperCurrency()||{},i=this.getPaymentMethodName(),r={step:e,currency:n};t&&(r.shipping_method=t.description),i&&(r.payment_method=i),r.shipping_method||r.payment_method||(r.shipping_method=" "),this.analytics.track("Checkout Step Completed",r);const o=t?t.id:"",a=e===yI.SHIPPING?`${e}-${o}`:e;this._completedSteps[a]=!0}getTrackingPayload({orderId:e,revenue:t,shipping:n,tax:i,discount:r,coupons:o,extraItemsData:a,lineItems:s}){const{code:d=""}=this.getShopperCurrency()||{},{storeName:c=""}=this.getStoreProfile()||{};return{order_id:String(e),affiliation:c,revenue:this.toShopperCurrency(t),shipping:this.toShopperCurrency(n),tax:this.toShopperCurrency(i),discount:this.toShopperCurrency(r),coupon:(o||[]).map(e=>e.code.toUpperCase()).join(","),currency:d,products:this.getProducts(a,s)}}hasStepCompleted(e){const t=this.getSelectedShippingOption(),n=t?t.id:"";return Object.prototype.hasOwnProperty.call(this._completedSteps,e)||e===yI.SHIPPING&&Object.prototype.hasOwnProperty.call(this._completedSteps,`${e}-${n}`)}hasStepViewed(e){return!!this._viewedSteps[e]}getIdFromStep(e){const t=e.split(".");return gI[t[0]]||null}trackViewed(e){const t=this.getShopperCurrency();this.analytics.track("Checkout Step Viewed",{step:e,currency:t?t.code:""}),this._viewedSteps[e]=!0}getOrder(){const{data:{getOrder:e}}=this.checkoutService.getState();return e()}getCheckout(){const{data:{getCheckout:e}}=this.checkoutService.getState();return e()}getShopperCurrency(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.shopperCurrency}getStoreProfile(){const{data:{getConfig:e}}=this.checkoutService.getState(),t=e();return t&&t.storeProfile}toShopperCurrency(e){const{exchangeRate:t=1}=this.getShopperCurrency()||{};return Math.round(e*t*100)/100}getSelectedShippingOption(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedShippingOption();return t&&t.id&&t.description?t:null}getPaymentMethodName(){const{data:e}=this.checkoutService.getState(),t=e.getSelectedPaymentMethod();return t&&t.config&&t.config.displayName||""}getProducts(e,t){const n=(t.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,price:e.listPrice,quantity:e.quantity,name:e.name})),i=t.giftCertificates.map(e=>({product_id:e.id,price:this.toShopperCurrency(e.amount),name:e.name,quantity:1}));return[...n,...[...t.physicalItems,...t.digitalItems].map(t=>{let n;t.options&&t.options.length&&(n=t.options.map(e=>`${e.name}:${e.value}`),n.sort());const i=Array.isArray(n)&&n.length?n.join(", "):"single-product-option",r=e[t.productId]&&e[t.productId].brand;return Object.assign({product_id:String(t.productId),sku:t.sku,price:t.salePrice,image_url:t.imageUrl,name:t.name,quantity:t.quantity,category:e[t.productId]?e[t.productId].category:"",variant:i},r&&{brand:r})}),...i]}}class vI{trackCheckoutStarted(){}trackOrderComplete(){}trackStepViewed(){}trackStepCompleted(){}}function _I(e,t){const{data:n}=e.getState(),i=n.getConfig();if(!i)throw new ot(tt.MissingCheckoutConfig);const{isAnalyticsEnabled:r}=i.checkoutSettings;return r&&pl(window)?new fI(e,new hl(Te),window.analytics,t):new vI}function SI(e){return Boolean(e.hasOwnProperty("braintreeFastlane"))}class II{constructor(e){this.checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this.checkoutService.getState(),t=e.data.getPaymentMethod("braintree")||e.data.getPaymentMethod("braintreeacceleratedcheckout"),n=null==t?void 0:t.initializationData.isBraintreeAnalyticsV2Enabled,i=SI(window)&&window.braintreeFastlane.events;return n&&i}_getBraintreeEventsOrThrow(){if(SI(window))return window.braintreeFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getBraintreeEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getBraintreeEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getBraintreeEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this.checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a=n.data.getPaymentMethod("braintreeacceleratedcheckout"),s=[{treatment_group:!n.errors.getLoadPaymentMethodError("braintreeacceleratedcheckout")&&(null==a?void 0:a.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id)||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(s)}}_getEmailSubmittedEventOptions(){const e=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this.checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function wI(e){return new II(e)}class CI{constructor(e){this._checkoutService=e,this._selectedPaymentMethodId=""}customerPaymentMethodExecuted(){this._shouldTrackFastlaneEvent()&&this._trackEmailSubmitted()}paymentComplete(){this._shouldTrackFastlaneEvent()&&this._trackOrderPlaced(this._selectedPaymentMethodId)}selectedPaymentMethod(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!1))}walletButtonClick(e){this._shouldTrackFastlaneEvent()&&e&&(this._selectedPaymentMethodId=e,this._trackApmSelected(e,!0))}_shouldTrackFastlaneEvent(){const e=this._checkoutService.getState().data.getPaymentMethod("paypalcommerce"),t=((null==e?void 0:e.initializationData)||{}).isPayPalCommerceAnalyticsV2Enabled,n=window,i=!!n.paypalFastlane&&!!n.paypalFastlane.events;return t&&i}_getPayPalEventsOrThrow(){const e=window;if(e.paypalFastlane&&e.paypalFastlane.events)return e.paypalFastlane.events;throw new mi}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getPayPalEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:n}=this._getPayPalEventsOrThrow();n(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getPayPalEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const n=this._checkoutService.getState(),i=n.data.getCart(),r=null===(e=n.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=n.data.getCustomer())||void 0===t?void 0:t.isGuest,a="paypalcommerceacceleratedcheckout",s=n.data.getPaymentMethod(a),d=[{treatment_group:!n.errors.getLoadPaymentMethodError(a)&&(null==s?void 0:s.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==i?void 0:i.id.replace(/-/g,""))||"",page_type:"checkout_page",page_name:window.document.title,partner_name:"bigc",user_type:o?"store_guest":"store_member",store_id:(null==r?void 0:r.storeId)||"",merchant_name:(null==r?void 0:r.storeName)||"",experiment:JSON.stringify(d)}}_getEmailSubmittedEventOptions(){const e=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{user_email_saved:!1,apm_shown:e.length>1?"1":"0",apm_list:e.join(",")})}_getApmSelectedEventOptions(e,t){const n=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:e,apm_location:t?"pre-email section":"payment section"})}_getOrderPlacedEventOptions(e){const t=this._checkoutService.getState().data.getCart();return Object.assign(Object.assign({},this._getEventCommonOptions()),{selected_payment_method:e,currency_code:(null==t?void 0:t.currency.code)||""})}}function bI(e){return new CI(e)}var PI;class OI{constructor(e,t){this._host=e,this._hostedFormFactory=t}submitStoredCard(e,t){return n=this,i=void 0,o=function*(){const n=this._hostedForm;if(!n)throw new gn(ln.PaymentNotInitialized);yield n.validate().then(()=>n.submitStoredCard({fields:e,data:t}))},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 n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r(function(e){e(n)})).then(a,s)}d((o=o.apply(n,i||[])).next())});var n,i,r,o}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}function EI(e){const t=gS();return new OI(e,new wy(t))}!function(e){e.CUSTOMER="customer",e.SHIPPING="shipping",e.BILLING="billing",e.PAYMENT="payment"}(PI||(PI={}));const AI=[PI.CUSTOMER,PI.SHIPPING,PI.BILLING,PI.PAYMENT];class TI{constructor(e,t){this.subscribe=e,this.bodlEvents=t,this._checkoutStarted=!1,this._emailEntryBegan=!1,this._shippingOptionsShown=!1,this._completedSteps={},this.subscribe(e=>{var t;if(this.setState(e.data),!(null===(t=this.state)||void 0===t?void 0:t.getConfig()))throw new ot(tt.MissingCheckoutConfig)})}setState(e){this.state=e}checkoutBegin(){const e=this._getCommonCheckoutData();!this._checkoutStarted&&e&&(this.bodlEvents.emitCheckoutBeginEvent(e),this._checkoutStarted=!0)}orderPurchased(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getOrder();if(!t)return;const{currency:n,isComplete:i,orderId:r,orderAmount:o,shippingCostTotal:a,lineItems:s,cartId:d,coupons:c,channelId:l,taxTotal:u}=t;i&&this.bodlEvents.emitOrderPurchasedEvent({event_id:d,currency:n.code,order_id:r,tax:u,channel_id:l,cart_value:o,coupon_codes:c.map(e=>e.code.toUpperCase()),shipping_cost:a,line_items:this._getProducts(s,n.code)})}stepCompleted(e){e&&AI.some(t=>(this._hasStepCompleted(t)||this._trackCompletedStep(t),t===e))}customerEmailEntry(e){!this._emailEntryBegan&&(null==e?void 0:e.length)&&(this._emailEntryBegan=!0,this.bodlEvents.emit("bodl_checkout_email_entry_began"))}customerSuggestionInit(e){this.bodlEvents.emit("bodl_checkout_customer_suggestion_initialization",e)}customerSuggestionExecute(){this.bodlEvents.emit("bodl_checkout_customer_suggestion_execute")}customerPaymentMethodExecuted(e){this.bodlEvents.emit("bodl_checkout_customer_payment_method_executed",e)}showShippingMethods(){this._shippingOptionsShown||(this._shippingOptionsShown=!0,this.bodlEvents.emit("bodl_checkout_show_shipping_options"))}selectedPaymentMethod(e){const t=this._getCommonCheckoutData();t&&e&&this.bodlEvents.emitPaymentDetailsProvidedEvent(Object.assign(Object.assign({},t),{payment_type:e}))}clickPayButton(e){this.bodlEvents.emit("bodl_checkout_click_pay_button",e)}paymentRejected(){this.bodlEvents.emit("bodl_checkout_payment_rejected")}paymentComplete(){this.bodlEvents.emit("bodl_checkout_payment_complete")}exitCheckout(){this.bodlEvents.emit("bodl_checkout_exit")}_trackCompletedStep(e){this._completedSteps[e]=!0;const t={[PI.SHIPPING]:this._trackShippingStepCompleted.bind(this)}[e];t?t():this.bodlEvents.emit("bodl_checkout_step_completed",{step:e})}_trackShippingStepCompleted(){var e,t;const n=null===(t=null===(e=this.state)||void 0===e?void 0:e.getSelectedShippingOption())||void 0===t?void 0:t.description,i=this._getCommonCheckoutData();i&&n&&this.bodlEvents.emitShippingDetailsProvidedEvent(Object.assign(Object.assign({},i),{shipping_method:n}))}_getCommonCheckoutData(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getCheckout();if(!t)return null;const{cart:{cartAmount:n,currency:i,lineItems:r,id:o,coupons:a},channelId:s}=t;return{event_id:o,currency:i.code,cart_value:n,coupon_codes:a.map(e=>e.code.toUpperCase()),line_items:this._getProducts(r,i.code),channel_id:s}}_getProducts(e,t){const n=(e.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,base_price:e.listPrice,sale_price:e.listPrice,purchase_price:e.listPrice,quantity:e.quantity,product_name:e.name,currency:t})),i=e.giftCertificates.map(e=>({product_id:e.id,gift_certificate_id:e.id,base_price:e.amount,sale_price:e.amount,purchase_price:e.amount,product_name:e.name,gift_certificate_name:e.name,gift_certificate_theme:e.theme,quantity:1,currency:t}));return[...n,...[...e.physicalItems,...e.digitalItems].map(e=>{let n;return e.options&&e.options.length&&(n=e.options.map(e=>`${e.name}:${e.value}`),n.sort()),{product_id:e.productId,quantity:e.quantity,product_name:e.name,base_price:e.listPrice,sale_price:e.salePrice,purchase_price:e.salePrice>0?e.salePrice:e.listPrice,sku:e.sku,variant_id:e.variantId,discount:e.discountAmount,coupon_amount:e.couponAmount,brand_name:e.brand,currency:t,category_names:(i=e,Array.isArray(i.categoryNames)?i.categoryNames:Array.isArray(i.categories)?q(i.categories).map(({name:e})=>e):[]),retail_price:e.retailPrice};var i}),...i].map(e=>Object.assign(Object.assign({},e),{product_id:String(e.product_id)}))}_hasStepCompleted(e){return this._completedSteps[e]}}class kI{checkoutBegin(){}orderPurchased(){}stepCompleted(){}customerEmailEntry(){}customerSuggestionInit(){}customerSuggestionExecute(){}customerPaymentMethodExecuted(){}showShippingMethods(){}selectedPaymentMethod(){}clickPayButton(){}paymentRejected(){}paymentComplete(){}exitCheckout(){}}function DI(e){return function(e){return"bodlEvents"in e}(window)?new TI(e,window.bodlEvents.checkout):new kI}export{Bn as ExtensionCommandType,Un as ExtensionQueryType,DI as createBodlService,wI as createBraintreeAnalyticTracker,US as createCheckoutButtonInitializer,fS as createCheckoutService,lI as createCurrencyService,nI as createEmbeddedCheckoutMessenger,sI as createLanguageService,bI as createPayPalCommerceAnalyticTracker,_I as createStepTracker,EI as createStoredCardHostedFormService,i as createTimeout,KS as embedCheckout,$e as isExtraField};
|
|
2
2
|
//# sourceMappingURL=checkout-sdk-essential.js.map
|