@bigcommerce/checkout-sdk 1.863.0 → 1.864.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +10 -0
- package/docs/README.md +1 -0
- package/docs/interfaces/InventorySettings.md +50 -0
- package/docs/interfaces/StoreConfig.md +7 -0
- 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 i,createTimeout as n}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{cond as m,constant as y,difference as g,each as v,filter as f,find as S,findIndex as w,flatMap as I,flatten as _,get as C,identity as b,includes as P,isArray as O,isEmpty as E,isEqual as A,isMatch as T,isNil as k,isObject as D,isPlainObject as M,isString as z,isUndefined as N,kebabCase as x,keyBy as F,keys as R,last as L,map as B,max as j,memoize as U,merge as q,noop as V,omit as G,omitBy as H,overSome as $,pick as W,pickBy as Y,reduce as K,round as J,some as Z,stubTrue as X,transform as Q,union as ee,uniq as te,uniqueId as ie,values as ne,without as re}from"lodash";import{Observable as oe,Subject as ae,concat as se,defer as de,empty as ce,from as le,fromEvent as ue,merge as he,noop as pe,of as me,throwError as ye}from"rxjs";import{catchError as ge,delay as ve,distinctUntilChanged as fe,filter as Se,map as we,retryWhen as Ie,shareReplay as _e,switchMap as Ce,take as be}from"rxjs/operators";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 Ne,stringifyUrl as xe}from"query-string";import{createSelector as Fe,createSelectorCreator as Re,defaultMemoize as Le}from"reselect";import{default as Be}from"shallowequal";import{IntlMessageFormat as je}from"intl-messageformat";import{default as Ue}from"messageformat";var qe={785:t=>{t.exports=e},939:e=>{e.exports=t}},Ve={};function Ge(e){var t=Ve[e];if(void 0!==t)return t.exports;var i=Ve[e]={exports:{}};return qe[e](i,i.exports,Ge),i.exports}Ge.d=(e,t)=>{for(var i in t)Ge.o(t,i)&&!Ge.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},Ge.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ge.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var He={};Ge.r(He),Ge.d(He,{createAmazonPayV2CustomerStrategy:()=>wn,createApplePayCustomerStrategy:()=>Jn,createBigCommercePaymentsCustomerStrategy:()=>Ir,createBigCommercePaymentsFastlaneCustomerStrategy:()=>qr,createBigCommercePaymentsPayLaterCustomerStrategy:()=>Hr,createBigCommercePaymentsVenmoCustomerStrategy:()=>Yr,createBoltCustomerStrategy:()=>ro,createBraintreeFastlaneCustomerStrategy:()=>ko,createBraintreePaypalCreditCustomerStrategy:()=>Co,createBraintreePaypalCustomerStrategy:()=>wo,createBraintreeVisaCheckoutCustomerStrategy:()=>zo,createGooglePayAdyenV2CustomerStrategy:()=>oa,createGooglePayAdyenV3CustomerStrategy:()=>aa,createGooglePayAuthorizeDotNetCustomerStrategy:()=>da,createGooglePayBigCommercePaymentsCustomerStrategy:()=>Za,createGooglePayBnzCustomerStrategy:()=>ga,createGooglePayBraintreeCustomerStrategy:()=>qa,createGooglePayCheckoutComCustomerStrategy:()=>pa,createGooglePayCybersourceCustomerStrategy:()=>ya,createGooglePayOrbitalCustomerStrategy:()=>fa,createGooglePayPayPalCommerceCustomerStrategy:()=>Ya,createGooglePayStripeCustomerStrategy:()=>Fa,createGooglePayStripeUpeCustomerStrategy:()=>Ra,createGooglePayTdOnlineMartCustomerStrategy:()=>ts,createGooglePayWorldpayAccessCustomerStrategy:()=>Ba,createPayPalCommerceCreditCustomerStrategy:()=>Is,createPayPalCommerceCustomerStrategy:()=>fs,createPayPalCommerceFastlaneCustomerStrategy:()=>Hs,createPayPalCommerceVenmoCustomerStrategy:()=>bs,createStripeLinkV2CustomerStrategy:()=>ad,createStripeUPECustomerStrategy:()=>Ks});var $e={};Ge.r($e),Ge.d($e,{createAdyenV2PaymentStrategy:()=>wd,createAdyenV3PaymentStrategy:()=>Pd,createAffirmPaymentStrategy:()=>kd,createAfterpayPaymentStrategy:()=>Rd,createAmazonPayV2PaymentStrategy:()=>jd,createApplePayPaymentStrategy:()=>Gd,createBigCommercePaymentsAlternativeMethodsPaymentStrategy:()=>vc,createBigCommercePaymentsCreditCardsPaymentStrategy:()=>mc,createBigCommercePaymentsFastlanePaymentStrategy:()=>ec,createBigCommercePaymentsPayLaterPaymentStrategy:()=>nc,createBigCommercePaymentsPaymentStrategy:()=>Jd,createBigCommercePaymentsRatePayPayPaymentStrategy:()=>sc,createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy:()=>Sc,createBigCommercePaymentsVenmoPaymentStrategy:()=>_c,createBlueSnapDirectAPMPaymentStrategy:()=>qc,createBlueSnapDirectCreditCardPaymentStrategy:()=>jc,createBlueSnapV2PaymentStrategy:()=>Wc,createBoltPaymentStrategy:()=>el,createBraintreeAchPaymentStrategy:()=>rl,createBraintreeCreditCardPaymentStrategy:()=>Nl,createBraintreeFastlanePaymentStrategy:()=>wl,createBraintreeLocalMethodsPaymentStrategy:()=>gl,createBraintreePaypalPaymentStrategy:()=>hl,createBraintreeVenmoPaymentStrategy:()=>Ol,createBraintreeVisaCheckoutPaymentStrategy:()=>Cl,createCBAMPGSPaymentStrategy:()=>Ul,createCheckoutComAPMPaymentStrategy:()=>nu,createCheckoutComCreditCardPaymentStrategy:()=>Jl,createCheckoutComFawryPaymentStrategy:()=>Hl,createCheckoutComIdealPaymentStrategy:()=>eu,createCheckoutComSepaPaymentStrategy:()=>Xl,createClearpayPaymentStrategy:()=>su,createCreditCardPaymentStrategy:()=>du,createCyberSourcePaymentStrategy:()=>Cu,createCyberSourceV2PaymentStrategy:()=>Au,createExternalPaymentStrategy:()=>ku,createGooglePayAdyenV2PaymentStrategy:()=>Fu,createGooglePayAdyenV3PaymentStrategy:()=>Bu,createGooglePayAuthorizeNetPaymentStrategy:()=>ju,createGooglePayBigCommercePaymentsPaymentStrategy:()=>ih,createGooglePayBraintreePaymentStrategy:()=>$u,createGooglePayCheckoutComPaymentStrategy:()=>Uu,createGooglePayCybersourcePaymentStrategy:()=>qu,createGooglePayOrbitalPaymentStrategy:()=>Vu,createGooglePayPPCPPaymentStrategy:()=>Zu,createGooglePayStripePaymentStrategy:()=>Gu,createGooglePayTdOnlineMartPaymentStrategy:()=>nh,createGooglePayWorldpayAccessPaymentStrategy:()=>Hu,createHummPaymentStrategy:()=>ah,createKlarnaPaymentStrategy:()=>hh,createKlarnaV2PaymentStrategy:()=>vh,createLegacyPaymentStrategy:()=>Sh,createMolliePaymentStrategy:()=>Ph,createMonerisPaymentStrategy:()=>Th,createNoPaymentStrategy:()=>Dh,createOfflinePaymentStrategy:()=>zh,createOffsitePaymentStrategy:()=>Fh,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>ip,createPayPalCommerceCreditCardsPaymentStrategy:()=>op,createPayPalCommerceCreditPaymentStrategy:()=>Hh,createPayPalCommerceFastlanePaymentStrategy:()=>hp,createPayPalCommercePaymentStrategy:()=>Uh,createPayPalCommerceRatePayPaymentStrategy:()=>dp,createPayPalCommerceVenmoPaymentStrategy:()=>Yh,createPayPalProPaymentStrategy:()=>Pp,createPaypalExpressPaymentStrategy:()=>_p,createSagePayPaymentStrategy:()=>Ep,createSezzlePaymentStrategy:()=>Tp,createSquareV2PaymentStrategy:()=>Rp,createStripeCSPaymentStrategy:()=>om,createStripeOCSPaymentStrategy:()=>im,createStripeUPEPaymentStrategy:()=>Qp,createStripeV3PaymentStrategy:()=>Yp,createTDOnlineMartPaymentStrategy:()=>lm,createWorldpayAccessPaymentStrategy:()=>ym,createZipPaymentStrategy:()=>fm});var We,Ye,Ke={};function Je(e,t,i){return(n=t)&&n.type&&n.error?se(me(t),ye(h(e,t.payload,i))):ye(h(e,t,i));var n}Ge.r(Ke),Ge.d(Ke,{createAmazonPayV2ButtonStrategy:()=>rw,createApplePayButtonStrategy:()=>cw,createBigCommercePaymentsAlternativeMethodsButtonStrategy:()=>fw,createBigCommercePaymentsButtonStrategy:()=>hw,createBigCommercePaymentsPayLaterButtonStrategy:()=>yw,createBigCommercePaymentsVenmoButtonStrategy:()=>Iw,createBoltButtonStrategy:()=>Cw,createBraintreePaypalButtonStrategy:()=>Aw,createBraintreePaypalCreditButtonStrategy:()=>Dw,createBraintreeVenmoButtonStrategy:()=>jw,createBraintreeVisaCheckoutButtonStrategy:()=>Nw,createGooglePayAdyenV2ButtonStrategy:()=>$w,createGooglePayAdyenV3ButtonStrategy:()=>Ww,createGooglePayAuthorizeDotNetButtonStrategy:()=>Yw,createGooglePayBigCommercePaymentsButtonStrategy:()=>Hw,createGooglePayBraintreeButtonStrategy:()=>Vw,createGooglePayCheckoutComButtonStrategy:()=>Kw,createGooglePayCybersourceButtonStrategy:()=>Jw,createGooglePayOrbitalButtonStrategy:()=>Zw,createGooglePayPayPalCommerceButtonStrategy:()=>Gw,createGooglePayStripeButtonStrategy:()=>Xw,createGooglePayTdOnlineMartButtonStrategy:()=>eI,createGooglePayWorldpayAccessButtonStrategy:()=>Qw,createLinkV2ButtonStrategy:()=>fI,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>hI,createPayPalCommerceButtonStrategy:()=>nI,createPayPalCommerceCreditButtonStrategy:()=>aI,createPayPalCommerceVenmoButtonStrategy:()=>cI,createPaypalExpressButtonStrategy:()=>yI});class Ze 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"}(We||(We={}));class Xe extends Ze{constructor(e){super(function(e){switch(e){case We.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case We.MissingCart:return"Unable to proceed because cart data is unavailable.";case We.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case We.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case We.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case We.MissingCheckoutConfig:case We.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case We.MissingOrder:return"Unable to proceed because order data is unavailable.";case We.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case We.MissingPayment:return"Unable to proceed because payment data is unavailable.";case We.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case We.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case We.MissingPaymentProviderCustomer:return"Unable to proceed because payment provider customer is unavailable.";case We.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"}(Ye||(Ye={}));class Qe extends Ze{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 et;class tt{constructor(e,t){this._requestSender=e,this._subscriptionActionCreator=t}continueAsGuest(e,t){return i=>{const n=i.getState(),r=n.checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);const o=n.customer.getCustomer();if(o&&!o.isGuest)throw new Qe;const a=n.billingAddress.getBillingAddress();let s;if(a){const{country:t}=a,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(a,["country"]);s=Object.assign(Object.assign({},i),e)}else s=e;const d=!E(a);return he(se(me(l(Ye.ContinueAsGuestRequested)),de(()=>{return e=this,i=void 0,o=function*(){const{body:e}=yield this._createOrUpdateBillingAddress(r.id,s,d,t);return l(Ye.ContinueAsGuestSucceeded,e)},new((n=void 0)||(n=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 i;e.done?t(e.value):(i=e.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((o=o.apply(e,i||[])).next())});var e,i,n,o})).pipe(ge(e=>Je(Ye.ContinueAsGuestFailed,e))),this._updateCustomerConsent(e,t))}}updateAddress(e,t){return i=>oe.create(n=>{const r=i.getState(),o=r.checkout.getCheckout();if(!o)throw new Xe(We.MissingCheckout);n.next(l(Ye.UpdateBillingAddressRequested));const a=r.billingAddress.getBillingAddress(),s=!E(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})=>{n.next(l(Ye.UpdateBillingAddressSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Ye.UpdateBillingAddressFailed,e))})})}_updateCustomerConsent({email:e,acceptsAbandonedCartEmails:t,acceptsMarketingNewsletter:i},n){return null==t&&null==i?ce():this._subscriptionActionCreator.updateSubscriptions({email:e,acceptsMarketingNewsletter:i||!1,acceptsAbandonedCartEmails:t||!1},n)}_createOrUpdateBillingAddress(e,t,i,n){return i?this._requestSender.updateAddress(e,t,n):this._requestSender.createAddress(e,t,n)}}class it extends Ze{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"}(et||(et={}));const nt=et,rt={"X-Checkout-SDK-Version":"1.863.0"};const ot={include:["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"].join(",")};class at{constructor(e){this._requestSender=e}createAddress(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/billing-address`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(n,{body:t,params:ot,headers:r,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}updateAddress(e,t,{timeout:i}={}){const{id:n}=t,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(t,["id"]),o=`/api/storefront/checkouts/${e}/billing-address/${n}`,a=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.put(o,{params:ot,body:r,headers:a,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}}var st,dt;function ct(e,t){const i=u((e,t)=>t.type===st.Synchronize?t.payload:e,e.getState(),{stateTransformer:t});return e.subscribe(e=>{i.dispatch(l(st.Synchronize,e))},{initial:!1}),i}!function(e){e.Synchronize="SYNCHRONIZE"}(st||(st={}));class lt{log(e){console.error(e)}}!function(e){e.ClearError="CLEAR_ERROR"}(dt||(dt={}));class ut{clearError(e){return{type:dt.ClearError,payload:e}}}function ht(){try{return"production"}catch(e){return"development"}}class pt{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 mt{log(){}info(){}warn(){}error(){}debug(){}}const yt=function(e=!0){return e?new pt(console):new mt}("test"!==ht());function gt(){return yt}function vt(e,t,i){const n=new WeakMap;function r(e){return(...i)=>{const r=i[i.length-1],{useCache:o}=(a=r)&&"boolean"==typeof a.useCache?r:{useCache:!1};var a;if(!o)return e.call(this,...i);const s=n.get(this)||{};var d;return n.get(this)||n.set(this,s),s[t]||(s[t]=(d=e,Pe(function(...e){const t=d.call(this,...e);return t instanceof oe?le(t).pipe(_e()):"function"==typeof t?Pe(e=>le(t(e)).pipe(_e()),{isEqual:A}):t},{isEqual:A}))),s[t].call(this,...i)}}return{get(){if("function"!=typeof i.value)throw new Error("Decorator should be used in functions");const e=r.call(this,i.value);return Object.defineProperty(this,t,Object.assign(Object.assign({},i),{value:e})),e}}}var ft;!function(e){e.LoadConfigRequested="LOAD_CONFIG_REQUESTED",e.LoadConfigSucceeded="LOAD_CONFIG_SUCCEEDED",e.LoadConfigFailed="LOAD_CONFIG_FAILED"}(ft||(ft={}));class St{constructor(e){this._configRequestSender=e}loadConfig(e){return oe.create(t=>{t.next(l(ft.LoadConfigRequested)),this._configRequestSender.loadConfig(e).then(e=>{t.next(l(ft.LoadConfigSucceeded,e.body)),t.complete()}).catch(e=>{t.error(h(ft.LoadConfigFailed,e))})})}}!function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);o>3&&a&&Object.defineProperty(t,i,a)}([vt],St.prototype,"loadConfig",null);const wt={body:{},headers:{},status:0};class It extends Ze{constructor(e,{message:t,errors:i}={}){const{body:n,headers:r,status:o}=e||wt;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=n,this.headers=r,this.status=o,this.errors=i||[]}}class _t extends It{constructor(e){super(e,{message:e.body.title}),this.name="CheckoutNotAvailableError",this.type="checkout_not_available"}}const Ct="This API endpoint is for internal use only and may change in the future";class bt{constructor(e){this._requestSender=e}loadConfig({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-settings",{timeout:e,headers:Object.assign({Accept:nt.JsonV1,"X-API-INTERNAL":Ct},rt),params:t}).catch(e=>{if(e.status>=400&&e.status<500)throw new _t(e);throw e})}}var Pt;!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"}(Pt||(Pt={}));class Ot{constructor(e){this._couponRequestSender=e}applyCoupon(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);n.next(l(Pt.ApplyCouponRequested)),this._couponRequestSender.applyCoupon(r.id,e,t).then(({body:e})=>{n.next(l(Pt.ApplyCouponSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Pt.ApplyCouponFailed,e))})})}removeCoupon(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);n.next(l(Pt.RemoveCouponRequested)),this._couponRequestSender.removeCoupon(r.id,e,t).then(({body:e})=>{n.next(l(Pt.RemoveCouponSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Pt.RemoveCouponFailed,e))})})}}const Et=["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","customer.customerGroup","payments","promotions.banners"];var At,Tt,kt,Dt;function Mt(e){return te(e).join(",")}!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(At||(At={}));class zt{constructor(e){this._requestSender=e}applyCoupon(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/coupons`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(n,{headers:r,timeout:i,params:{include:Mt([...Et,At.AvailableShippingOptions])},body:{couponCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}removeCoupon(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/coupons/${t}`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.delete(n,{headers:r,timeout:i,params:{include:Mt([...Et,At.AvailableShippingOptions])}}).catch(e=>{if("empty_cart"===e.body.type)throw new it;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"}(Tt||(Tt={}));class Nt{constructor(e){this._giftCertificateRequestSender=e}applyGiftCertificate(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);n.next(l(Tt.ApplyGiftCertificateRequested)),this._giftCertificateRequestSender.applyGiftCertificate(r.id,e,t).then(({body:e})=>{n.next(l(Tt.ApplyGiftCertificateSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Tt.ApplyGiftCertificateFailed,e))})})}removeGiftCertificate(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);n.next(l(Tt.RemoveGiftCertificateRequested)),this._giftCertificateRequestSender.removeGiftCertificate(r.id,e,t).then(({body:e})=>{n.next(l(Tt.RemoveGiftCertificateSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Tt.RemoveGiftCertificateFailed,e))})})}}class xt{constructor(e){this._requestSender=e}applyGiftCertificate(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/gift-certificates`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(n,{headers:r,timeout:i,params:{include:Mt(Et)},body:{giftCertificateCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}removeGiftCertificate(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/gift-certificates/${t}`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.delete(n,{headers:r,timeout:i,params:{include:Mt(Et)}}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}}function Ft(e){return e&&"resolveIds"in e}function Rt(e,t){return Object.assign(e,{resolveIds:t})}class Lt extends Ze{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Bt{constructor(e){var t,i,n;this._factories={},this._instances={},this._defaultToken=null!==(t=null==e?void 0:e.defaultToken)&&void 0!==t?t:"default",this._useFallback=null===(i=null==e?void 0:e.useFallback)||void 0===i||i,this._tokenResolver=null!==(n=null==e?void 0:e.tokenResolver)&&void 0!==n?n: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 i=this._tokenResolver(e,Object.keys(this._factories),t);return i?this._factories[i]:void 0}register(e,t){if(this._hasFactory(e))throw new Lt(`'${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 i=this.getFactory(e);if(!i)throw new Lt(`'${e}' is not registered.`);this._instances[t]=i()}return this._instances[t]}}class jt{constructor(e=!1){this._useFallback=e,this._registry=new Bt({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,i){var n;const r=this._decodeToken(e),o=[];t.forEach(e=>{const t=this._decodeToken(e),i={token:e,matches:0,default:!1};for(const[e,n]of Object.entries(t)){if(e in r&&r[e]!==n){i.matches=0;break}e in r&&r[e]===n&&i.matches++,"default"===e&&!0===n&&(i.default=!0)}o.push(i)});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"===ht()&>().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=a[0];if(i&&(null==s?void 0:s.matches)!==Object.keys(r).length)throw new Error("Unable to resolve to a registered token with the provided token.");if(s&&s.token)return s.token;if(this._useFallback){const e=null===(n=o.find(e=>e.default))||void 0===n?void 0:n.token;if(e)return e}throw new Error("Unable to resolve to a registered token with the provided token.")}}function Ut(e){const t=e;return"object"==typeof t&&"object"==typeof t.payload&&"string"==typeof t.payload.token}!function(e){e.BuyNow="BUY_NOW"}(kt||(kt={})),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"}(Dt||(Dt={}));var qt,Vt,Gt;class Ht{constructor(e,t,i){this._customerRequestSender=e,this._checkoutActionCreator=t,this._spamProtectionActionCreator=i}createCustomer(e,t){return i=>{const n=i.getState().config.getStoreConfigOrThrow(),{isStorefrontSpamProtectionEnabled:r}=n.checkoutSettings,o=n=>le(this._customerRequestSender.createAccount(Object.assign(Object.assign({},e),{token:n}),t)).pipe(Ce(()=>se(this._checkoutActionCreator.loadCurrentCheckout(t)(i),me(l(Dt.CreateCustomerSucceeded)))));return se(me(l(Dt.CreateCustomerRequested)),r?le(this._spamProtectionActionCreator.execute()(i)).pipe(Ce(e=>{var t;return Ut(e)?se(me(e),o(null===(t=e.payload)||void 0===t?void 0:t.token)):me(e)})):o()).pipe(ge(e=>Je(Dt.CreateCustomerFailed,e)))}}createAddress(e,t){return se(me(l(Dt.CreateCustomerAddressRequested)),de(()=>{return i=this,n=void 0,o=function*(){const{body:i}=yield this._customerRequestSender.createAddress(e,t);return l(Dt.CreateCustomerAddressSucceeded,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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).pipe(ge(e=>Je(Dt.CreateCustomerAddressFailed,e)))}signInCustomer(e,t){return i=>{const n=i.getState().checkout.getCheckoutOrThrow(),r=n.cart.source===kt.BuyNow?n.id:void 0;return se(me(l(Dt.SignInCustomerRequested)),le(this._customerRequestSender.signInCustomer(Object.assign(Object.assign({},e),{cartId:r}),t)).pipe(Ce(({body:e})=>e.data.persistentCartRetrievalInformation?se(this._checkoutActionCreator.loadCheckout(e.data.persistentCartRetrievalInformation.id,t)(i),me(l(Dt.SignInCustomerSucceeded,e.data))):se(this._checkoutActionCreator.loadCurrentCheckout(t)(i),me(l(Dt.SignInCustomerSucceeded,e.data)))))).pipe(ge(e=>Je(Dt.SignInCustomerFailed,e)))}}signOutCustomer(e){return t=>{const i=t.getState().checkout.getCheckoutOrThrow(),n=i.cart.source===kt.BuyNow?i.id:void 0;return se(me(l(Dt.SignOutCustomerRequested)),le(this._customerRequestSender.signOutCustomer(e,n)).pipe(Ce(({body:i})=>se(this._checkoutActionCreator.loadCurrentCheckout(e)(t),me(l(Dt.SignOutCustomerSucceeded,i.data)))))).pipe(ge(e=>Je(Dt.SignOutCustomerFailed,e)))}}}class $t{constructor(e){this._requestSender=e}createAccount(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer",{timeout:t,headers:rt,body:e})}createAddress(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer-address",{timeout:t,headers:rt,body:e})}signInCustomer(e,{timeout:t}={}){return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:t,headers:rt,body:e})}signOutCustomer({timeout:e}={},t){return this._requestSender.delete("/internalapi/v1/checkout/customer",Object.assign({timeout:e,headers:rt},t&&{body:{cartId:t}}))}}function Wt(e,t,i=!0){var n;return null!==(n=e[t])&&void 0!==n?n:i}function Yt(e,t,i){t.forEach(t=>{Ft(t)&&t.resolveIds.forEach(n=>{if(e.getFactory(n,!0))return;const r=Rt(()=>t(i),t.resolveIds);e.register(n,r)})})}function Kt(e,t,i,n){const r=e.getFactory(i);if(!r)return;if(!t.some(e=>Jt(r,e))){const e=`A different strategy is registered for ${JSON.stringify(i)}.`;return new Error(e)}const o=new jt(e.getUseFallback());Yt(o,t,n);const a=o.getFactory(i);if(!a||!Jt(a,r)){const e=`A different strategy is resolved for ${JSON.stringify(i)}.`;return new Error(e)}}function Jt(e,t){return Ft(e)&&Ft(t)&&A(e.resolveIds,t.resolveIds)}!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"}(qt||(qt={}));class Zt{constructor(e,t,i,n){this._strategyRegistry=e,this._strategyRegistryV2=t,this._paymentIntegrationService=i,this._errorLogger=n}signIn(e,t){return oe.create(i=>{const n=t&&t.methodId,r={methodId:n};i.next(l(qt.SignInRequested,void 0,r)),this._getStrategy(n).signIn(e,t).then(()=>{i.next(l(qt.SignInSucceeded,void 0,r)),i.complete()}).catch(e=>{i.error(h(qt.SignInFailed,e,r))})})}signOut(e){return oe.create(t=>{const i=e&&e.methodId,n={methodId:i};t.next(l(qt.SignOutRequested,void 0,n)),this._getStrategy(i).signOut(e).then(()=>{t.next(l(qt.SignOutSucceeded,void 0,n)),t.complete()}).catch(e=>{t.error(h(qt.SignOutFailed,e,n))})})}executePaymentMethodCheckout(e){return oe.create(t=>{const i=e&&e.methodId,n={methodId:i};t.next(l(qt.ExecutePaymentMethodCheckoutRequested,void 0,n)),this._getStrategy(i).executePaymentMethodCheckout(e).then(()=>{t.next(l(qt.ExecutePaymentMethodCheckoutSucceeded,void 0,n)),t.complete()}).catch(e=>{t.error(h(qt.ExecutePaymentMethodCheckoutFailed,e,n))})})}initialize(e){return t=>oe.create(i=>{var n,r;const o=t.getState(),a=e&&e.methodId,s={methodId:a},{features:d}=o.config.getStoreConfigOrThrow().checkoutSettings;if(Wt(d,"CHECKOUT-9450.lazy_load_payment_strategies",!1)){const t={id:a||""},i=Kt(this._strategyRegistryV2,null!==(n=null==e?void 0:e.integrations)&&void 0!==n?n:[],t,this._paymentIntegrationService);i&&this._errorLogger.log(i),Yt(this._strategyRegistryV2,null!==(r=null==e?void 0:e.integrations)&&void 0!==r?r:[],this._paymentIntegrationService)}if(a&&o.customerStrategies.isInitialized(a))return i.complete();i.next(l(qt.InitializeRequested,void 0,s)),this._getStrategy(a).initialize(e).then(()=>{i.next(l(qt.InitializeSucceeded,void 0,s)),i.complete()}).catch(e=>{i.error(h(qt.InitializeFailed,e,s))})})}deinitialize(e){return t=>oe.create(i=>{const n=t.getState(),r=e&&e.methodId,o={methodId:r};if(r&&!n.customerStrategies.isInitialized(r))return i.complete();i.next(l(qt.DeinitializeRequested,void 0,o)),this._getStrategy(r).deinitialize(e).then(()=>{i.next(l(qt.DeinitializeSucceeded,void 0,o)),i.complete()}).catch(e=>{i.error(h(qt.DeinitializeFailed,e,o))})})}widgetInteraction(e,t){return oe.create(i=>{const n={methodId:t&&t.methodId};i.next(l(qt.WidgetInteractionStarted,void 0,n)),e().then(()=>{i.next(l(qt.WidgetInteractionFinished,void 0,n)),i.complete()}).catch(e=>{i.error(h(qt.WidgetInteractionFailed,e,n))})})}_getStrategy(e){let t;try{t=this._strategyRegistryV2.get({id:e||""})}catch(i){t=this._strategyRegistry.get(e)}return t}}function Xt(e,t=[]){return Array.isArray(t)?Mt([...e,...t]):function(e,t){const i=R(Y(t,e=>!e)),n=R(f(t));return Mt([...g(e,i),...n])}(e,t)}class Qt{constructor(e){this._requestSender=e}loadCheckout(e,{params:{include:t}={},timeout:i}={}){const n=`/api/storefront/checkout/${e}`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.get(n,{params:{include:Xt(Et,t)},headers:r,timeout:i}).catch(e=>{if(e.status>=400&&e.status<500)throw new _t(e);throw e})}updateCheckout(e,t,{params:{include:i}={},timeout:n}={}){const r=`/api/storefront/checkout/${e}`,o=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.put(r,{params:{include:Xt(Et,i)},body:t,headers:o,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new it;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"}(Vt||(Vt={})),function(e){e.HydrateInitialState="HYDRATE_INITIAL_STATE"}(Gt||(Gt={}));var ei;class ti{constructor(e,t,i){this._checkoutRequestSender=e,this._configActionCreator=t,this._formFieldsActionCreator=i}loadCheckout(e,t){return()=>se(me(l(Vt.LoadCheckoutRequested)),he(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})),de(()=>this._checkoutRequestSender.loadCheckout(e,t).then(({body:e})=>l(Vt.LoadCheckoutSucceeded,this._transformCustomerAddresses(e))))).pipe(ge(e=>Je(Vt.LoadCheckoutFailed,e)))}loadDefaultCheckout(e){return t=>se(me(l(Vt.LoadCheckoutRequested)),he(this._configActionCreator.loadConfig({useCache:!0,timeout:null==e?void 0:e.timeout}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==e?void 0:e.timeout})),de(()=>{return i=this,n=void 0,o=function*(){const i=t.getState().config.getContextConfig();if(!i||!i.checkoutId)throw new Xe(We.MissingCheckoutConfig);const{body:n}=yield this._checkoutRequestSender.loadCheckout(i.checkoutId,e);return l(Vt.LoadCheckoutSucceeded,this._transformCustomerAddresses(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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).pipe(ge(e=>Je(Vt.LoadCheckoutFailed,e)))}updateCheckout(e,t){return i=>new oe(n=>{const r=i.getState().checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);n.next(l(Vt.UpdateCheckoutRequested)),this._checkoutRequestSender.updateCheckout(r.id,e,t).then(({body:e})=>{n.next(l(Vt.UpdateCheckoutSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Vt.UpdateCheckoutFailed,e))})})}loadCurrentCheckout(e){return t=>{const i=t.getState().checkout.getCheckout();if(!i)throw new Xe(We.MissingCheckout);return this.loadCheckout(i.id,e)(t)}}hydrateInitialState(e){return{type:Gt.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"}(ei||(ei={}));var ii;class ni{constructor(e){this._formFieldsRequestSender=e}loadFormFields(e){return se(me(l(ei.LoadFormFieldsRequested)),de(()=>{return t=this,i=void 0,r=function*(){const{body:t}=yield this._formFieldsRequestSender.loadFields(e);return l(ei.LoadFormFieldsSucceeded,t)},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r})).pipe(ge(e=>Je(ei.LoadFormFieldsFailed,e)))}}!function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);o>3&&a&&Object.defineProperty(t,i,a)}([vt],ni.prototype,"loadFormFields",null);class ri{constructor(e){this._requestSender=e}loadFields({timeout:e}={}){return this._requestSender.get("/api/storefront/form-fields",{timeout:e,headers:Object.assign({Accept:nt.JsonV1,"X-API-INTERNAL":Ct},rt)})}}class oi extends Ze{constructor(){super("You haven't complete our spam protection challenge. Please try again."),this.name="SpamProtectionChallengeNotCompletedError",this.type="spam_protection_challenge_not_completed"}}class ai extends Ze{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"}(ii||(ii={}));var si,di,ci,li=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ui{constructor(e,t){this._googleRecaptcha=e,this._requestSender=t}initialize(e){return t=>se(me(l(ii.InitializeRequested,void 0)),de(()=>li(this,void 0,void 0,function*(){const i=e?e.containerId:"spamProtectionContainer";if(document.getElementById(i)&&this._googleRecaptcha.reset(i),!e&&!document.getElementById(i)){const e=document.createElement("div");e.setAttribute("id",i),document.body.appendChild(e)}const n=t.getState().config.getStoreConfigOrThrow().checkoutSettings.googleRecaptchaSitekey;return yield this._googleRecaptcha.load(i,n),l(ii.InitializeSucceeded)}))).pipe(ge(e=>Je(ii.InitializeFailed,e)))}verifyCheckoutSpamProtection(){return e=>de(()=>{const t=e.getState().checkout.getCheckout();if(!t)throw new Xe(We.MissingCheckout);return se(me(l(ii.VerifyCheckoutRequested)),le(this.execute()(e)).pipe(Ce(e=>Ut(e)&&e.payload?le(this._requestSender.validate(t.id,e.payload.token)).pipe(Ce(({body:t})=>se(me(e),me(l(ii.VerifyCheckoutSucceeded,t))))):me(e)))).pipe(ge(e=>Je(ii.VerifyCheckoutFailed,e)))})}execute(){return e=>se(me(l(ii.ExecuteRequested)),this.initialize()(e),this._googleRecaptcha.execute().pipe(be(1)).pipe(Ce(({error:e,token:t})=>li(this,void 0,void 0,function*(){if(e instanceof oi)throw e;if(e||!t)throw new ai;return l(ii.ExecuteSucceeded,{token:t})})))).pipe(ge(e=>Je(ii.ExecuteFailed,e)))}}class hi{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"}(si||(si={}));class pi extends Ze{constructor(e){super(function(e){switch(e){case si.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case si.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case si.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case si.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 mi extends Ze{constructor(){super("Spam protection is not loaded. Please try again."),this.name="SpamProtectionNotLoadedError",this.type="spam_protection_failed"}}class yi{constructor(e,t){this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=Pe((e,t,i)=>{const n=new ae;if(!i)throw new Error;return this._widgetId=e.render(i.id,{sitekey:t,size:"invisible",callback:()=>{n.next({token:e.getResponse(this._widgetId)}),e.reset(this._widgetId)},"error-callback":()=>{n.next({error:new ai})}}),n},{isEqual:(e,t)=>e===t})}load(e,t){return this.googleRecaptchaScriptLoader.load().then(i=>{i&&(this._event$=this._memoized(i,t,document.getElementById(e)),this._recaptcha=i)}).catch(e=>{throw e})}reset(e){var t;const i=document.getElementById(e);null==i||i.remove(),null===(t=this._recaptcha)||void 0===t||t.reset(this._widgetId)}execute(){return de(()=>{const e=this._event$,t=this._recaptcha;if(!e||!t)throw new pi(si.SpamProtectionNotInitialized);return de(()=>{const e=document.querySelector('iframe[src*="bframe"]');return e?me(e):ye(new mi)}).pipe(Ie(e=>e.pipe(ve(250),Ce((e,t)=>t<28?me(e):ye(e)))),Ce(i=>(this._watchRecaptchaChallengeWindow(e,i),t.execute(this._widgetId),e)),ge(e=>me({error:e})))})}_watchRecaptchaChallengeWindow(e,t){const i=t.parentElement;if(!i)throw new mi;const n=i.parentElement;if(!n)throw new mi;this.mutationObserverFactory.create(()=>{"hidden"===n.style.visibility&&e.next({error:new oi})}).observe(n,{attributes:!0,attributeFilter:["style"]})}}class gi{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((i,n)=>{this._window[e]=()=>i(this._window.grecaptcha),this._scriptLoader.loadScript(`//www.google.com/recaptcha/api.js?${t}`).catch(e=>{this._loadPromise=void 0,n(e)})})}}function vi(e){return new yi(new gi(e),new hi)}class fi{constructor(e){this._requestSender=e}validate(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/spam-protection`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(n,{body:{token:t},headers:r,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}}class Si{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 wi(e){if(!/^(https?:)?\/\//.test(e))throw new Lt("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const i=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}${i?`:${i}`:""}`,pathname:t.pathname,port:i,protocol:t.protocol,search:t.search}}class Ii extends Ze{constructor(e){super(e||"Unable to proceed due to no extension configured for this region."),this.name="ExtensionNotFoundError",this.type="extension_not_found"}}function _i(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"}(di||(di={}));class Ci{constructor(e,t,i){this._targetWindow=t,this._context=i,this._targetOrigin="*"===e?"*":wi(e).origin}post(e,t){const i=this._targetWindow;if(window===i)return;if(!i)throw new Error("Unable to post message because target window is not set.");const n=t&&ue(window,"message").pipe(Se(e=>e.origin===this._targetOrigin&&_i(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),we(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),be(1)).toPromise();return i.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),n}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}function bi(e){var t;const i=null===(t=document.querySelector(`[data-extension-id="${e.id}"]`))||void 0===t?void 0:t.querySelector("iframe");if(!(null==i?void 0:i.contentWindow))throw new Ii(`Unable to post due to no extension rendered for ID: ${e.id}.`);return new Ci(e.url,i.contentWindow)}!function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(ci||(ci={}));class Pi{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}class Oi extends Ze{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 Ei;class Ai{constructor(e){this._mutationObserver=e}ensurePresence(e,t){return i=this,n=void 0,o=function*(){const i=new Pi(t),n=this._mutationObserver.create(t=>{t.forEach(t=>{0!==Array.from(t.removedNodes).filter(t=>e.some(e=>t===e||t.contains(e))).length&&i.cancel(new Oi)})});n.observe(document.body,{childList:!0,subtree:!0});try{const e=yield i.promise;return n.disconnect(),e}catch(e){throw n.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}function Ti(e,t){const{iframeResizer:i}=Ge(785);return i(e,t)}class ki extends Ze{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"}(Ei||(Ei={}));class Di{constructor(e){this._options=e}createFrame(e,t,i,n){const r=document.getElementById(t),{timeout:o=6e4}=this._options||{};if(!r)throw new ki("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,i,n).catch(e=>{throw r.removeChild(a),e})}_toResizableFrame(e,t,i,n){return r=this,o=void 0,s=function*(){const r=new Ai(new hi),o=new Promise((r,o)=>{const a=window.setTimeout(()=>{try{n()}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 ki("Unable to load the extension because the content could not be loaded."))},t),s=t=>{if(t.origin===wi(e.src).origin&&_i(t.data,Ei.ResizeIframe)){e.style.display="";const t=Ti({autoResize:!1,scrolling:!1,sizeWidth:!1,heightCalculationMethod:"bodyOffset",initCallback:i},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 i(e){try{d(s.next(e))}catch(e){t(e)}}function n(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(i,n)}d((s=s.apply(r,o||[])).next())});var r,o,a,s}}class Mi{constructor(e,t,i){this._containerId=e,this._extension=t,this._config=i;const{cartId:n,parentOrigin:r}=this._config;this._url=new URL(this._extension.url),this._url.searchParams.set("extensionId",this._extension.id),this._url.searchParams.set("cartId",n),this._url.searchParams.set("parentOrigin",r)}attach(){var e,t,i,n,r;return t=this,i=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 Di,i=e=>{bi(this._extension).post({type:e})};this._iframe=yield t.createFrame(this._url.toString(),this._containerId,()=>{i(ci.ExtensionReady)},()=>{i(ci.ExtensionFailed)});const n=document.getElementById(this._containerId);null==n||n.setAttribute("data-extension-id",this._extension.id)},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())})}detach(){this._iframe&&this._iframe.parentElement&&this._iframe.parentElement.removeChild(this._iframe)}}class zi{constructor(e){this._requestSender=e}loadExtensions(e){return()=>oe.create(t=>{t.next(l(di.LoadExtensionsRequested)),this._requestSender.loadExtensions(e).then(e=>{const i=e.body;t.next(l(di.LoadExtensionsSucceeded,i)),t.complete()}).catch(e=>{t.error(h(di.LoadExtensionsFailed,e))})})}renderExtension(e,t,i){return n=>oe.create(r=>{return o=this,a=void 0,d=function*(){const o=n.getState(),{id:a}=o.cart.getCartOrThrow(),{links:{checkoutLink:s},checkoutSettings:{features:d}}=o.config.getStoreConfigOrThrow();if(!d["PROJECT-5029.checkout_extension"])return r.complete();const c=o.extensions.getExtensionByRegion(t);try{if(!c)throw new Ii(`Unable to proceed due to no extension configured for the region: ${t}.`);if(r.next(l(di.RenderExtensionRequested)),"worker"===c.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")}}(c.url);i.add(c.id,e)}else{const t=new Mi(e,c,{cartId:a,parentOrigin:wi(s).origin});yield t.attach()}r.next(l(di.RenderExtensionSucceeded)),r.complete()}catch(e){r.error(h(di.RenderExtensionFailed,e))}},new((s=void 0)||(s=Promise))(function(e,t){function i(e){try{r(d.next(e))}catch(e){t(e)}}function n(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(i,n)}r((d=d.apply(o,a||[])).next())});var o,a,s,d})}}class Ni{constructor(e){this._requestSender=e}loadExtensions({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-extensions",{timeout:e,headers:Object.assign({Accept:nt.JsonV1},rt),params:t})}}const xi=function(e,t,i){return t&&i?Fi(0,t,i):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(i=>{const n=Object.getOwnPropertyDescriptor(e.prototype,i);n&&"constructor"!==i&&Object.defineProperty(t.prototype,i,Fi(e.prototype,i,n))}),t}(e)};function Fi(e,t,i){if("function"!=typeof i.value)return i;let n=i.value;return{get(){const e=n.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},i),{value:e})),e},set(e){n=e}}}var Ri,Li;class Bi{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 i=this._listeners[e];i||(this._listeners[e]=i=[]),-1===i.indexOf(t)&&i.push(t)}removeListener(e,t){const i=this._listeners[e];if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}trigger(e,t){const i=this._listeners[e.type];i&&i.forEach(i=>t?i(e,t):i(e))}_handleMessage(e){const t=e.data,{context:i}=t,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(t,["context"]);this.trigger(n,i)}}!function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);o>3&&a&&Object.defineProperty(t,i,a)}([xi],Bi.prototype,"_handleMessage",null);class ji{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 Ui extends Ze{constructor(e){super(e||"Unable to proceed due to unsupported extension command."),this.name="UnsupportedExtensionCommandError",this.type="unsupported_extension_command_error"}}class qi extends Ze{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"}(Ri||(Ri={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(Li||(Li={}));class Vi{constructor(e={},t={},i={}){this._workers=e,this._commandListeners=t,this._queryListeners=i}add(e,t){this._workers[e]=t}listenForCommand(e,t,i){const n=this._getWorkerById(e);this._commandListeners[e]||(this._commandListeners[e]=new Bi(n));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,n)=>{(null==n?void 0:n.extensionId)===e&&i(t,n)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,i){const n=this._getWorkerById(e);this._queryListeners[e]||(this._queryListeners[e]=new Bi(n));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,n)=>{(null==n?void 0:n.extensionId)===e&&i(t,n)};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 ji(this._workers[e],e).post(t)}clearCacheById(e){delete this._workers[e]}_getWorkerById(e){const t=this._workers[e];if(!t)throw new Ii(`Worker with extensionId ${e} not found`);return t}_validateCommand(e){if(Object.values(Ri).includes(e))return e;throw new Ui}_validateQuery(e){if(Object.values(Li).includes(e))return e;throw new qi}}function Gi(e){return wi(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,`www.${e.hostname}`))}var Hi;class $i{constructor(e){this._sourceOrigins=[wi(e).origin,Gi(wi(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 i=this._listeners[e];i||(this._listeners[e]=i=[]),-1===i.indexOf(t)&&i.push(t)}removeListener(e,t){const i=this._listeners[e];if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}trigger(e,t){const i=this._listeners[e.type];i&&i.forEach(i=>t?i(e,t):i(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!_i(e.data,e.data.type))return;const t=e.data,{context:i}=t,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(t,["context"]);this.trigger(n,i)}}!function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);o>3&&a&&Object.defineProperty(t,i,a)}([xi],$i.prototype,"_handleMessage",null);class Wi{constructor(e,t,i={},n={},r={}){this._store=e,this._workerExtensionMessenger=t,this._commandListeners=i,this._queryListeners=n,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,i){const n=this._getExtensionById(e);if("worker"===n.type)return this._workerExtensionMessenger.listenForCommand(e,t,i);this._commandListeners[e]||(this._commandListeners[e]=new $i(n.url));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,n)=>{(null==n?void 0:n.extensionId)===e&&i(t,n)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,i){const n=this._getExtensionById(e);if("worker"===n.type)return this._workerExtensionMessenger.listenForQuery(e,t,i);this._queryListeners[e]||(this._queryListeners[e]=new $i(n.url));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,n)=>{(null==n?void 0:n.extensionId)===e&&i(t,n)};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 i=this._getExtensionById(e);if("worker"===i.type)return void this._workerExtensionMessenger.post(e,t);this._posters[e]||(this._posters[e]=bi(i)),this._posters[e].post(t)}catch(i){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 i=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.id===e);if(!i)throw new Ii(`Unable to proceed due to no extension found for ID: ${e}.`);return i}_getExtensionByRegion(e){var t;this._getExtensions();const i=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.region===e);if(!i)throw new Ii(`Unable to proceed due to no extension found for region: ${e}.`);return i}_getExtensions(){if(this._extensions)return;const{extensions:{getExtensions:e}}=this._store.getState();if(this._extensions=e(),!this._extensions)throw new Ii("Extension configurations not found.")}_validateCommand(e){if(Object.values(Ri).includes(e))return e;throw new Ui}_validateQuery(e){if(Object.values(Li).includes(e))return e;throw new qi}}class Yi{constructor(e,t,i){this._store=e,this._extensionMessenger=t,this._subscribers=i,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 $i(e.url);t.addListener(Ei.Subscribe,this._handleSubscribe.bind(this)),t.addListener(Ei.Unsubscribe,this._handleUnsubscribe.bind(this)),t.listen(),this._listeners[e.id]=t})}broadcast(e){var t;const{data:{getExtensions:i}}=this._store.getState();null===(t=i())||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 i,n;delete this._subscribed[t],Object.keys(this._subscribed).length||(null===(n=(i=this._unsubscribers)[e])||void 0===n||n.call(i),delete this._unsubscribers[e])}}!function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}(Hi||(Hi={}));const Ki=(e,t)=>{var i;const{data:{getConsignments:n}}=e.getState();let r=null!==(i=n())&&void 0!==i?i:[];return e.subscribe(({data:{getConsignments:e}})=>{var i;const n=null!==(i=e())&&void 0!==i?i:[];n!==r&&(t.broadcast({type:Hi.ConsignmentsChanged,payload:{consignments:n,previousConsignments:r}}),r=n)},({data:{getConsignments:e}})=>e())};class Ji 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 Zi,Xi;!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"}(Zi||(Zi={}));class Qi extends Ji{constructor(e){super(function(e){switch(e){case Zi.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case Zi.MissingCart:return"Unable to proceed because cart data is unavailable.";case Zi.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case Zi.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case Zi.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case Zi.MissingCheckoutConfig:case Zi.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case Zi.MissingOrder:return"Unable to proceed because order data is unavailable.";case Zi.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case Zi.MissingPayment:return"Unable to proceed because payment data is unavailable.";case Zi.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case Zi.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case Zi.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 en(e){return t=e.lineItems.physicalItems.filter(e=>!e.addedByPromotion),K(t,(e,t)=>e+t.quantity,0);var t}function tn(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"}(Xi||(Xi={}));class nn extends Ji{constructor(e){super(function(e){switch(e){case Xi.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Xi.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Xi.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Xi.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 rn={de:"eu",jp:"fe",uk:"eu",us:"na"};var on,an,sn,dn,cn,ln;!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"}(on||(on={})),function(e){e.Home="Home",e.Product="Product",e.Cart="Cart",e.Checkout="Checkout",e.Other="Other"}(an||(an={})),function(e){e.USD="USD",e.EUR="EUR",e.GBP="GBP",e.JPY="JPY"}(sn||(sn={})),function(e){e.PayAndShip="PayAndShip",e.PayOnly="PayOnly"}(dn||(dn={})),function(e){e.Gold="Gold",e.LightGray="LightGray",e.DarkGray="DarkGray"}(cn||(cn={})),function(e){e.C0001="C0001"}(ln||(ln={}));var un=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class hn{constructor(e){this.amazonPayV2ScriptLoader=e}initialize(e){return un(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,i){this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${e}`,{amazonCheckoutSessionId:t,changeAction:i})}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(()=>un(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 un(this,void 0,void 0,function*(){return this.amazonPayV2SDK&&this.amazonPayV2SDK.Pay.signout(),Promise.resolve()})}renderAmazonPayButton({buttonColor:e,checkoutState:t,containerId:i,decoupleCheckoutInitiation:n=!1,methodId:r,options:o,placement:a,isButtonMicroTextDisabled:s=!1}){const d=document.querySelector(`#${i}`);if(!d)return;const{id:c}=d.appendChild(this.getButtonParentContainer());o&&s&&(o.design=ln.C0001);const l=null!=o?o:this.getAmazonPayV2ButtonOptions(t,r,a,n,e);return this.createButton(c,l),this.getButtonParentContainer()}updateBuyNowFlowFlag(e){this.isBuyNowFlow=Boolean(e)}isPh4Enabled(e,t){const i=!!e["PROJECT-3483.amazon_pay_ph4"],n=!!e["INT-6885.amazon_pay_ph4_us_only"];return i&&n?"US"===t:i}prepareRequestConfig(e,t,i){const{publicKeyId:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["publicKeyId"]);return Object.assign(Object.assign({createCheckoutSessionConfig:this.isEnvironmentSpecific(n)?r:e},t&&{estimatedOrderAmount:t}),i&&{productType:i})}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,i,n=!1,r=cn.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 Qi(Zi.MissingPaymentMethod);const{checkoutLanguage:p,checkoutSessionMethod:m,createCheckoutSessionConfig:y,extractAmazonCheckoutSessionId:g,ledgerCurrency:v,publicKeyId:f="",isButtonMicroTextDisabled:S}=h;if(!l||!v)throw new Qi(Zi.MissingPaymentMethod);const w=Object.assign({merchantId:l,ledgerCurrency:v,checkoutLanguage:p,placement:i,buttonColor:r},S?{design:ln.C0001}:{});if(this.isBuyNowFlow)return Object.assign(Object.assign({},w),{sandbox:!!u});const I=a();w.productType=I&&0===en(I)?dn.PayOnly:dn.PayAndShip;const{checkoutSettings:{features:_},storeProfile:{shopPath:C,storeCountryCode:b}}=d();if(this.isPh4Enabled(_,b)){if(!y)throw new Qi(Zi.MissingPaymentMethod);const e=null===(o=s())||void 0===o?void 0:o.outstandingBalance.toString(),t=null==I?void 0:I.currency.code,i=Object.assign({},w);let r;return this.isEnvironmentSpecific(f)?(i.publicKeyId=f,r=y):(i.sandbox=!!u,r=Object.assign(Object.assign({},y),{publicKeyId:f})),n||(i.createCheckoutSessionConfig=r),e&&t&&(i.estimatedOrderAmount={amount:e,currencyCode:t}),i}const P={method:m,url:`${C}/remote-checkout/${t}/payment-session`,extractAmazonCheckoutSessionId:g};return Object.assign(Object.assign({},w),{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 tn(e,()=>new nn(Xi.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 pn extends Ji{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 mn{constructor(e,t=window){this.scriptLoader=e,this.windowWithAmazonPay=t}load(e){return t=this,i=void 0,r=function*(){const{initializationData:t}=e,i=(null==t?void 0:t.region)||"us",n=rn[i];if(yield this.scriptLoader.loadScript(`https://static-${n}.payments-amazon.com/checkout.js`),!this.windowWithAmazonPay.amazon)throw new pn;return this.windowWithAmazonPay.amazon},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}function yn(){return new hn(new mn(a()))}class gn extends Ji{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class vn extends Ji{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var fn=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Sn{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return fn(this,void 0,void 0,function*(){const{methodId:t,amazonpay:i}=e;if(!t||!(null==i?void 0:i.container))throw new gn('Unable to proceed because "methodId" or "containerId" argument is not provided.');let n;try{n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}catch(e){yield this.paymentIntegrationService.loadPaymentMethod(t),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}yield this.amazonPayV2PaymentProcessor.initialize(n),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:i.container,methodId:t,placement:an.Checkout})})}deinitialize(){return fn(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize()})}signIn(){throw new vn('In order to sign in via Amazon, the shopper must click on "Amazon Pay" button.')}signOut(e){return fn(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 wn=Rt(e=>new Sn(e,yn()),[{id:"amazonpay"}]),In="3.128.0",_n="3.123.2",Cn="3.106.0";class bn{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()||(Wt(t,"PAYPAL-5809.braintree_hosted_fields_fix_version")?In:Wt(t,"PAYPAL-5636.update_braintree_sdk_version")?_n:Cn)}getPreloadedSDKVersion(){const e=this.braintreeWindow.braintree;if(e){const t=S(Object.values(e),e=>!!e.VERSION);return null==t?void 0:t.VERSION}}}class Pn extends Ji{constructor(e){super(e||"Unsupported browser error"),this.name="UnsupportedBrowserError",this.type="unsupported_browser"}}var On,En,An,Tn,kn,Dn,Mn;function zn(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"}(On||(On={})),function(e){e.Completed="COMPLETED",e.Pending="PENDING",e.Failed="FAILED"}(En||(En={})),function(e){e.TRUSTLY="trustly"}(An||(An={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="cancelled",e.UNRECOGNIZED="unrecognized"}(Tn||(Tn={})),function(e){e.Customer="CUSTOMER",e.Merchant="MERCHANT",e.Network="NETWORK",e.Internal="INTERNAL",e.Unknown="UNKNOWN"}(kn||(kn={})),function(e){e.KountNotEnabled="DATA_COLLECTOR_KOUNT_NOT_ENABLED"}(Dn||(Dn={})),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"}(Mn||(Mn={}));var Nn,xn,Fn,Rn=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ln{constructor(e){this.braintreeScriptLoader=e}initialize(e){this.setClientToken(e)}deinitialize(){return Rn(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollector),this.dataCollector=void 0})}getClient(){return Rn(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 Rn(this,void 0,void 0,function*(){const t={deviceData:void 0,teardown:()=>Promise.resolve()};if(!this.dataCollector)try{const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadDataCollector(),n=Object.assign({client:t,kount:!0},e);this.dataCollector=yield i.create(n)}catch(e){if(zn(e)&&e.code===Dn.KountNotEnabled)return t;throw e}return this.dataCollector})}getBraintreeGooglePayment(){return Rn(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 Rn(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 Rn(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment){const[t,i]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadLocalPayment()]);this.braintreeLocalPayment=yield new Promise((n,r)=>{i.create({client:t,merchantAccountId:e},(e,t)=>{e&&r(e),n(t)})})}return this.braintreeLocalPayment})}getUsBankAccount(){return Rn(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 Rn(this,void 0,void 0,function*(){return this.visaCheckoutSDK||(this.visaCheckoutSDK=yield this.braintreeScriptLoader.loadVisaCheckoutSdk(e)),this.visaCheckoutSDK})}getVenmoCheckoutOrThrow(){return Rn(this,void 0,void 0,function*(){if(!this.braintreeVenmo){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadVenmoCheckout(),i={client:e,allowDesktop:!0,paymentMethodUsage:"multi_use"},n=yield t.create(i);if(!n.isBrowserSupported())throw new Pn;this.braintreeVenmo=n}return this.braintreeVenmo})}setClientToken(e){this.clientToken=e}getClientTokenOrThrow(){if(!this.clientToken)throw new nn(Xi.PaymentNotInitialized);return this.clientToken}teardownModule(e){return e?e.teardown():Promise.resolve()}}!function(e){e.Sandbox="sandbox",e.Production="production"}(Nn||(Nn={})),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"}(xn||(xn={})),function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(Fn||(Fn={}));const Bn={[Cn]:{[xn.Client]:"sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt",[xn.PaypalCheckout]:"sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O",[xn.Paypal]:"sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+",[xn.LocalPayment]:"sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT",[xn.DataCollector]:"sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV",[xn.UsBankAccount]:"sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ",[xn.GooglePayment]:"sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe",[xn.ThreeDSecure]:"sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB",[xn.VisaCheckout]:"sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT",[xn.Venmo]:"sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov",[xn.HostedFields]:"sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy",[xn.Fastlane]:"sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa"},[_n]:{[xn.Client]:"sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO",[xn.PaypalCheckout]:"sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/",[xn.Paypal]:"sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt",[xn.LocalPayment]:"sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH",[xn.DataCollector]:"sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO",[xn.UsBankAccount]:"sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW",[xn.GooglePayment]:"sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO",[xn.ThreeDSecure]:"sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym",[xn.VisaCheckout]:"sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS",[xn.Venmo]:"sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU",[xn.HostedFields]:"sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P",[xn.Fastlane]:"sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y"},[In]:{[xn.Client]:"sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq",[xn.PaypalCheckout]:"sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh",[xn.Paypal]:"sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH",[xn.LocalPayment]:"sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC",[xn.DataCollector]:"sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc",[xn.UsBankAccount]:"sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F",[xn.GooglePayment]:"sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i",[xn.ThreeDSecure]:"sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D",[xn.VisaCheckout]:"sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv",[xn.Venmo]:"sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz",[xn.HostedFields]:"sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z",[xn.Fastlane]:"sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr"}};var jn,Un=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class qn{constructor(e,t,i){this.scriptLoader=e,this.braintreeHostWindow=t,this.braintreeSDKVersionManager=i}loadClient(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.Client,"client.min.js")})}loadFastlane(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.Fastlane,"fastlane.min.js")})}loadPaypalCheckout(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.PaypalCheckout,"paypal-checkout.min.js")})}loadPaypal(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.Paypal,"paypal.min.js")})}loadLocalPayment(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.LocalPayment,"local-payment.min.js")})}loadDataCollector(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.DataCollector,"data-collector.min.js")})}loadUsBankAccount(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.UsBankAccount,"us-bank-account.min.js")})}loadGooglePayment(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.GooglePayment,"google-payment.min.js")})}load3DS(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.ThreeDSecure,"three-d-secure.min.js")})}loadVisaCheckout(){return this.loadBraintreeModuleOrThrow(xn.VisaCheckout,"visa-checkout.min.js")}loadVenmoCheckout(){return this.loadBraintreeModuleOrThrow(xn.Venmo,"venmo.min.js")}loadHostedFields(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.HostedFields,"hosted-fields.min.js")})}loadVisaCheckoutSdk(e){return Un(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 pn;return this.braintreeHostWindow.V})})}loadBraintreeModuleOrThrow(e,t){return Un(this,void 0,void 0,function*(){let i=this.getBraintreeModule(e);if(i)return i;const n=this.braintreeSDKVersionManager.getSDKVersion(),r=`//js.braintreegateway.com/web/${n}/js/${t}`,o=n in Bn?this.getIntegrityValuesByModuleName(e,n):void 0;if(yield this.scriptLoader.loadScript(r,o?{async:!0,attributes:{integrity:o,crossorigin:"anonymous"}}:void 0),i=this.getBraintreeModule(e),!i)throw new pn;return i})}getBraintreeModule(e){var t;return null===(t=this.braintreeHostWindow.braintree)||void 0===t?void 0:t[e]}getIntegrityValuesByModuleName(e,t){const i=Bn[t][e];if(!i)throw new Error("Unexpected fileName value");return i}}class Vn extends Ji{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}!function(e){e.BRAINTREE="braintree",e.BRAINTREE_FASTLANE="braintreeacceleratedcheckout"}(jn||(jn={}));var Gn,Hn=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(Gn||(Gn={}));class $n{constructor(e,t,i,n,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=i,this._braintreeSdk=n,this._applePayScriptLoader=r,this._onAuthorizeCallback=V,this._onError=V,this._onClick=V,this._subTotalLabel=Gn.Subtotal,this._shippingLabel=Gn.Shipping,this._hasApplePaySession=!1}initialize(e){var t;return Hn(this,void 0,void 0,function*(){const{methodId:i,applepay:n}=e;if(!i||!n)throw new Qi(Zi.MissingPaymentMethod);const{container:r,shippingLabel:o,subtotalLabel:a,onError:s=V,onClick:d=V,onPaymentAuthorize:c}=n;this._shippingLabel=o||Gn.Shipping,this._subTotalLabel=a||Gn.Subtotal,this._onAuthorizeCallback=c,this._onError=s,this._onClick=d;let l=this._paymentIntegrationService.getState();yield this._applePayScriptLoader.loadSdk();try{this._paymentMethod=l.getPaymentMethodOrThrow(i)}catch(e){l=yield this._paymentIntegrationService.loadPaymentMethod(i),this._paymentMethod=l.getPaymentMethodOrThrow(i)}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)===jn.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken)})}deinitialize(){return Promise.resolve()}signIn(){throw new vn('In order to sign in via Apple, the shopper must click on "Apple Pay" button.')}signOut(){throw new vn("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 gn("Unable to create sign-in button without valid container ID.");const i=this._createApplePayButtonElement();return t.appendChild(i),i}_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(),i=t.getCartOrThrow(),n=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new Qi(Zi.MissingPaymentMethod);const o=this._getBaseRequest(i,r,n,this._paymentMethod),a=this._sessionFactory.create(o);this._handleApplePayEvents(a,this._paymentMethod,n),a.begin(),this._hasApplePaySession=!0}_getBaseRequest(e,t,i,n){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=i,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=n,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,i){e.onvalidatemerchant=i=>Hn(this,void 0,void 0,function*(){try{const{body:n}=yield this._onValidateMerchant(t,i);e.completeMerchantValidation(n)}catch(e){this._onError(e)}}),e.onshippingcontactselected=t=>Hn(this,void 0,void 0,function*(){return this._handleShippingContactSelected(e,i,t)}),e.onshippingmethodselected=t=>Hn(this,void 0,void 0,function*(){return this._handleShippingMethodSelected(e,i,t)}),e.oncancel=()=>Hn(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 Vn)}}),e.onpaymentauthorized=i=>Hn(this,void 0,void 0,function*(){return this._onPaymentAuthorized(i,e,t)})}_handleShippingContactSelected(e,t,i){var n;return Hn(this,void 0,void 0,function*(){const r=this._transformContactToAddress(i.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===(n=d.consignments[0].selectedShippingOption)||void 0===n?void 0:n.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,i){return Hn(this,void 0,void 0,function*(){const{storeProfile:{storeName:n}}=t,{shippingMethod:{identifier:r}}=i;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:n,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_getUpdatedLineItems(e,t){const i=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>i.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),i.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),i}_updateShippingOption(e){return Hn(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return Hn(this,void 0,void 0,function*(){const i=[`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:i})})}_onPaymentAuthorized(e,t,i){var n;return Hn(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===(n=i.initializationData)||void 0===n?void 0:n.gateway)===jn.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:i.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 Hn(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}function Wn(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}class Yn{create(e){return Wn(window),new ApplePaySession(1,e)}}class Kn{constructor(e){this.scriptLoader=e,this.sdkVersion="1.latest"}loadSdk(){return e=this,t=void 0,n=function*(){(function(e){return"ApplePaySDK"in e})(window)||(yield this.scriptLoader.loadScript(`https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`),Wn(window))},new((i=void 0)||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())});var e,t,i,n}}const Jn=Rt(e=>{const{getHost:t}=e.getState(),n=new bn(e);return new $n(i({host:t()}),e,new Yn,new Ln(new qn(a(),window,n)),new Kn(new r))},[{id:"applepay"}]);class Zn extends Ji{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 Xn={body:{},headers:{},status:0};class Qn extends Ji{constructor(e,{message:t,errors:i}={}){const{body:n,headers:r,status:o}=e||Xn;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=n,this.headers=r,this.status=o,this.errors=i||[]}}var er,tr,ir,nr,rr,or,ar;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(er||(er={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(tr||(tr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(ir||(ir={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(nr||(nr={})),function(e){e.pill="pill",e.rect="rect"}(rr||(rr={})),function(e){e.OXXO="oxxo"}(or||(or={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(ar||(ar={}));var sr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class dr{constructor(e,t,i,n){this.formPoster=e,this.paymentIntegrationService=t,this.bigCommercePaymentsRequestSender=i,this.bigCommercePaymentsScriptLoader=n}loadPayPalSdk(e,t,i,n){return sr(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,i,n),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new pn;return this.paypalSdk}createBuyNowCartOrThrow(e){return sr(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new Zn}})}createOrder(e,t){return sr(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:i},t));return n})}createOrderCardFields(e,t){return sr(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n,setupToken:r}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:i},t));return Object.assign({orderId:n},r?{setupToken:r}:{})})}updateOrder(){return sr(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getConsignmentsOrThrow()[0];try{yield this.bigCommercePaymentsRequestSender.updateOrder({availableShippingOptions:i.availableShippingOptions,cartId:t.id,selectedShippingOption:i.selectedShippingOption})}catch(e){throw new Qn}})}getOrderStatus(e,t){return sr(this,void 0,void 0,function*(){try{const{status:i}=yield this.bigCommercePaymentsRequestSender.getOrderStatus(e,t);return i}catch(e){throw new Qn}})}tokenizePayment(e,t){const i=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new Qi(Zi.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},i.source===kt.BuyNow&&{cart_id:i.id}))}submitPayment(e,t,i){return sr(this,void 0,void 0,function*(){const n={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:n},i?{gatewayId:i}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],i=t.availableShippingOptions||[],n=i.find(e=>e.isRecommended),r=(e?i.find(t=>t.id===e):i.find(e=>{var i;return e.id===(null===(i=t.selectedShippingOption)||void 0===i?void 0:i.id)}))||n||i[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,i;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===(i=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===i?void 0:i.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:i}=e,{address:n,name:{full_name:r}}=i[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:n.address_line_1,address2:n.address_line_2,city:n.admin_area_2,countryCode:n.country_code,postalCode:n.postal_code,stateOrProvinceCode:n.admin_area_1})}getValidButtonStyle(e){const{color:t,height:i,label:n,shape:r}=e||{},o={color:t&&nr[t]?t:void 0,height:this.getValidHeight(i),label:n&&ir[n]?n:void 0,shape:r&&rr[r]?r:void 0};return H(o,k)}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 cr="This API endpoint is for internal use only and may change in the future";var lr;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(lr||(lr={}));const ur=lr,hr={"X-Checkout-SDK-Version":"1.863.0"};var pr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class mr{constructor(e){this.requestSender=e}createOrder(e,t){return pr(this,void 0,void 0,function*(){const i=`/api/storefront/payment/${e}`,n=t,r=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.post(i,{headers:r,body:n})).body})}updateOrder(e){return pr(this,void 0,void 0,function*(){const t=e,i=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.put("/api/storefront/initialization/bigcommerce_payments",{headers:i,body:t})).body})}getOrderStatus(e="bigcommerce_payments",t){return pr(this,void 0,void 0,function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body})}}var yr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class gr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,i,n){return yr(this,void 0,void 0,function*(){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,i);return this.loadPayPalSDK(r,n)})}loadPayPalSDK(e,t=!1){return yr(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),i=this.transformConfig(e.attributes),n=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(n,{async:!0,attributes:i})}if(!this.window.paypal)throw new pn;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,i=!0){const{id:n,clientToken:r,initializationData:o}=e;if(!(null==o?void 0:o.clientId))throw new Qi(Zi.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:v}=o,f=h||i,S="bigcommerce_payments_creditcards"===n,w=S?["card"]:[],I=S?[]:["card"],_=p?["credit","paylater"]:[],C=p?[]:["credit","paylater"],b=u?["venmo"]:[],P=u?[]:["venmo"],O=y.filter(e=>!g.includes(e)),E=v?["googlepay"]:[],A=i?["card-fields"]:[],T=this.filterFundingOptions([...I,...C,...P,...O]),k=this.filterFundingOptions([...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:f,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}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}const vr=e=>{const{getHost:t}=e.getState();return new dr(Ee(),e,new mr(i({host:t()})),new gr(a()))},fr=40;var Sr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class wr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=V}initialize(e){return Sr(this,void 0,void 0,function*(){const{bigcommerce_payments:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.bigcommerce_payments.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.bigcommerce_payments.onClick" argument is not a function.');this.onError=t.onError||V,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 Sr(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Sr(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){const{container:i,onClick:n,onComplete: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"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},n&&{onClick:()=>n()}),u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,i)=>this.onHostedCheckoutApprove(t,i,e,r)},h=Object.assign(Object.assign({fundingSource:o.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},c),{height:fr}))},l),s&&u),p=o.Buttons(h);p.isEligible()?p.render(`#${i}`):this.bigCommercePaymentsIntegrationService.removeElement(i)}onHostedCheckoutApprove(e,t,i,n){return Sr(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Sr(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 Sr(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 Ir=Rt(e=>new wr(e,vr(e)),[{id:"bigcommerce_payments"}]);var _r,Cr,br,Pr,Or,Er,Ar,Tr,kr,Dr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Mr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,i){return Dr(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const n=this.getPayPalFastlaneSdkConfiguration(e,t,i);if(yield this.loadPayPalSdk(n),!this.window.paypalFastlaneSdk)throw new pn}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,i,n){return Dr(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||n){const n=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i);yield this.loadPayPalSdk(n)}if(!this.window.paypalGooglePay)throw new pn;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t){return Dr(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new pn}return this.window.paypalApms})}getPayPalMessages(e,t){return Dr(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new pn;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Dr(this,void 0,void 0,function*(){const i=this.transformConfig(e),n=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(i).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:n})})}getPayPalFastlaneSdkConfiguration(e,t,i){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.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":i.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":n}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i=!0){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||i;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":n,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:n,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=i,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:n},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{clientId:n,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=i;return{options:Object.assign({"client-id":n,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"paypalMessages","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(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}function zr(){return new Mr(o())}!function(e){e.CVV="cvv",e.PAN="pan"}(_r||(_r={}));class Nr{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,i=document.cookie;let n=null;const r=i.indexOf(t);if(r>-1){let e=i.indexOf(";",r);-1===e&&(e=i.length),n=decodeURIComponent(i.substring(r+t.length,e))}return n}static set(e,t,i={secure:!0}){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:r,path:o,domain:a,secure:s}=i;if(r)n+=`; expires=${r.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),n+=`; expires=${e.toUTCString()}`}o&&(n+=`; path=${o}`),a&&(n+=`; domain=${a}`),s&&(n+="; secure"),document.cookie=n}static remove(e,t){Nr.set(e,"",Object.assign({expires:new Date(0)},t))}}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Cr||(Cr={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(br||(br={})),function(e){e.Always="SCA_ALWAYS"}(Pr||(Pr={})),function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(Or||(Or={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Er||(Er={})),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"}(Tr||(Tr={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(kr||(kr={}));var xr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Fr{constructor(){this.window=window}initializePayPalFastlane(e,t,i){return xr(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:i||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new pn;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return xr(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return xr(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 i={expires:t,secure:!0};Nr.set("bc-fastlane-sessionId",e,i)}removeStorageSessionId(){Nr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Nr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var i,n,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(n=null===(i=null==a?void 0:a.card)||void 0===i?void 0:i.paymentSource)||void 0===n?void 0:n.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||kr.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:i,paymentSource:n}=t,{brand:r,expiry:o,lastDigits:a}=n.card,[s,d]=o.split("-");return[{bigpayToken:i,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:_r.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,i,n){const[r,o]=t.fullName.split(" "),a=(null==i?void 0:i.nationalNumber)||"",s=(null==i?void 0:i.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:n||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return A(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return G(e,["id","phone"])}}function Rr(){return new Fr}function Lr(e){return"string"!=typeof e}function Br(e,t){if(t||e)return function(e){var t,i;const n={},r=H(e.root,Lr),o=H(e.input,Lr),a=H(e.toggle,Lr),s=H(null===(t=e.text)||void 0===t?void 0:t.body,Lr),d=H(null===(i=e.text)||void 0===i?void 0:i.caption,Lr),c=e.branding;return Object.keys(r).length&&(n.root=r),Object.keys(o).length&&(n.input=o),Object.keys(a).length&&(n.toggle=a),Object.keys(s).length&&(n.text={},n.text.body=s),Object.keys(d).length&&(n.text=Object.assign({},n.text),n.text.caption=d),c&&(n.branding=c),n}(function(e,t){var i,n,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,w,I,_,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(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===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var jr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ur{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsSdk=t,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){var t;return jr(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_fastlane:n}=e;if(!i)throw new gn('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(i);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(i),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(i,n))}catch(e){}return Promise.resolve()})}deinitialize(){return jr(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return jr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return jr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return jr(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:i,methodId:n}=e||{};if(!n)throw new gn('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof i)throw new gn('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(n)}catch(e){}}i()})}runPayPalAuthenticationFlowOrThrow(e){return jr(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow().id,n=t.getCustomer(),r=t.getBillingAddress(),o=(null==n?void 0:n.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===kr.CANCELED;yield this.updateCustomerDataState(e,s),d?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(i)})}updateCustomerDataState(e,t){var i;return jr(this,void 0,void 0,function*(){const n=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&&n.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),n=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=n.initializationData||{},o=t.getConsignments()||[],a=(null===(i=o[0])||void 0===i?void 0:i.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 i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:n,isFastlaneStylingEnabled:r}=i.initializationData||{};return Br(r?n:{},null==t?void 0:t.styles)}}const qr=Rt(e=>new Ur(e,zr(),Rr()),[{id:"bigcommerce_payments_fastlane"},{id:"bigcommerce_payments_creditcards"}]);var Vr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Gr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=V}initialize(e){return Vr(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater.onClick" argument is not a function.');this.onError=t.onError||V,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Vr(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:i,onComplete:n,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,i)=>this.onHostedCheckoutApprove(t,i,e,n)},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:fr}))},l),s&&u),n=o.Buttons(t);n.isEligible()&&(n.render(`#${i}`),p=!0)}}),p||this.bigCommercePaymentsIntegrationService.removeElement(i)}onHostedCheckoutApprove(e,t,i,n){return Vr(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Vr(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 Vr(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 Hr=Rt(e=>new Gr(e,vr(e)),[{id:"bigcommerce_payments_paylater"}]);var $r=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Wr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return $r(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 $r(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return $r(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:i,onClick:n}=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:fr})),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},n&&{onClick:()=>n()}),c=r.Buttons(d);c.isEligible()?c.render(`#${i}`):this.bigCommercePaymentsIntegrationService.removeElement(i)}}const Yr=Rt(e=>new Wr(e,vr(e)),[{id:"bigcommerce_payments_venmo"}]);class Kr extends Ji{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 Jr extends Qn{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 Zr,Xr,Qr,eo=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class to{constructor(e,t){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=window}initialize(e){var t;return eo(this,void 0,void 0,function*(){const{methodId:i,bolt:n}=e,{onInit:r}=n||{};if(!i)throw new gn('Unable to proceed because "methodId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);if(!(null===(t=o.initializationData)||void 0===t?void 0:t.publishableKey))throw new Qi(Zi.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 eo(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return eo(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){return eo(this,void 0,void 0,function*(){const{continueWithCheckoutCallback:t=pe,checkoutPaymentMethodExecuted:i,methodId:n}=e||{},r=this.getCustomerEmail();if(!n)throw new gn('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof t)throw new gn('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(r)return this.openBoltCheckoutModalOrThrow(r,n,t,i);t()})}openBoltCheckoutModalOrThrow(e,t,i,n){var r;return eo(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:()=>{i()}};yield o.openCheckout(e,t)}else i();"function"==typeof n&&n({hasBoltAccount:t})}else i()}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 Kr(e.message);throw e}})}getBoltClientOrThrow(){const e=this.boltHostWindow.BoltCheckout;if(!e)throw new nn(Xi.PaymentNotInitialized);return e}hasBoltAccount(e){return eo(this,void 0,void 0,function*(){const t=this.getBoltClientOrThrow();try{return yield t.hasBoltAccount(e)}catch(e){throw new Jr}})}getCustomerEmail(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),i=e.getBillingAddress();return(null==t?void 0:t.email)||(null==i?void 0:i.email)||""}}!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(Zr||(Zr={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(Xr||(Xr={})),function(e){e.Pill="pill",e.Rect="rect"}(Qr||(Qr={}));var io=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class no{constructor(e,t=window){this.scriptLoader=e,this.boltHostWindow=t}loadBoltClient(e,t,i,n,r){return io(this,void 0,void 0,function*(){if(this.boltHostWindow.BoltCheckout)return this.boltHostWindow.BoltCheckout;if(!e)throw new gn('Unable to initialize payment because "publishableKey" argument is not provided.');if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,i)}/connect-bigcommerce.js`,this.getScriptOptions("bolt-connect",e,n,r)),yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,i)}/track.js`,this.getScriptOptions("bolt-track",e)),!this.boltHostWindow.BoltCheckout)throw new pn;return this.boltHostWindow.BoltCheckout})}loadBoltEmbedded(e,t,i){return io(this,void 0,void 0,function*(){if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,i)}/embed.js`,{async:!0,attributes:{id:"bolt-embedded"}}),!this.boltHostWindow.Bolt)throw new pn;return this.boltHostWindow.Bolt(e)})}getDomainURL(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case Zr.StagingMode:return"connect-staging.bolt.com";case Zr.DevelopmentMode:return`connect.${t.developerDomain}`}return"connect-sandbox.bolt.com"}getScriptOptions(e,t,i,n){return{async:!0,attributes:Object.assign(Object.assign({id:e,"data-publishable-key":t},i&&{"data-shopping-cart-id":i}),n&&{"data-storefront-api-token":n})}}}const ro=Rt(e=>new to(e,new no(a())),[{id:"bolt"}]);class oo extends gn{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 ao extends Ji{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 so=null;const co=["buttons","messages"];var lo,uo,ho,po,mo,yo;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(lo||(lo={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(uo||(uo={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(ho||(ho={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(po||(po={})),function(e){e.PILL="pill",e.RECT="rect"}(mo||(mo={})),function(e){e.CART="cart",e.HOME="homepage",e.PAYMENT="payment",e.PRODUCT="product"}(yo||(yo={}));var go=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class vo{constructor(e,t,i){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.overlay=i,this.dataCollectors={}}initialize(e,t){this.clientToken=e,this.threeDSecureOptions=t}getBraintreeFastlane(e,t,i){return go(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("axoEnv","sandbox"),window.localStorage.setItem("fastlaneEnv","sandbox")),!this.braintreeHostWindow.braintreeFastlane){const t=this.getClientTokenOrThrow(),n=yield this.getClient(),r=yield this.getSessionId(e),o=yield this.braintreeScriptLoader.loadFastlane(),a={root:{backgroundColorPrimary:"transparent"}};this.braintreeHostWindow.braintreeFastlane=yield o.create({authorization:t,client:n,deviceData:r,styles:i||a})}return this.braintreeHostWindow.braintreeFastlane})}getClient(){return go(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=t.create({authorization:e})}return this.client})}getPaypal(){return this.braintreePaypal||(this.braintreePaypal=Promise.all([this.getClient(),this.braintreeScriptLoader.loadPaypal()]).then(([e,t])=>t.create({client:e}))),this.braintreePaypal}paypal(e){var{shouldSaveInstrument:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["shouldSaveInstrument"]);const n=Ae();return this.getPaypal().then(e=>{var r;return n&&(null===(r=this.overlay)||void 0===r||r.show({onClick:()=>e.focusWindow()})),e.tokenize(Object.assign({enableShippingAddress:!0,flow:t?"vault":"checkout",useraction:"commit"},i))}).then(e=>{var t;return null===(t=this.overlay)||void 0===t||t.remove(),e}).catch(e=>{var t;throw null===(t=this.overlay)||void 0===t||t.remove(),e})}getPaypalCheckout(e,t,i){return go(this,void 0,void 0,function*(){const n=yield this.getClient(),r=yield this.braintreeScriptLoader.loadPaypalCheckout(),o={client:n};return this.paypalCheckout=yield r.create(o,(n,r)=>{var o;if(n)return i(n);const a=Object.assign(Object.assign({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:co.toString(),intent:e.intent,commit:null===(o=e.commit)||void 0===o||o});this.braintreeHostWindow.paypal?t(r):function(e,t){return so||(so=new Promise((i,n)=>{e.loadPayPalSDK(t,t=>{t?(so=null,n(t)):i(e)})})),so}(r,a).then(()=>t(r))}),this.paypalCheckout})}getDataCollector(e){return go(this,void 0,void 0,function*(){const t=(null==e?void 0:e.paypal)?"paypal":"default";let i=this.dataCollectors[t];if(!i){try{const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadDataCollector(),r=Object.assign({client:t,kount:!0},e);i=yield n.create(r)}catch(e){if(!zn(e)||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==e.code)throw e;i={deviceData:void 0,teardown:()=>Promise.resolve()}}this.dataCollectors[t]=i}return i})}getBraintreeEnv(e=!1){return e?Nn.Sandbox:Nn.Production}mapToBraintreeShippingAddressOverride(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}mapToLegacyShippingAddress(e){const{email:t,phone:i,shippingAddress:n}=e,r=(null==n?void 0:n.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:i,address_line_1:null==n?void 0:n.line1,address_line_2:null==n?void 0:n.line2,city:null==n?void 0:n.city,state:null==n?void 0:n.state,country_code:null==n?void 0:n.countryCode,postal_code:null==n?void 0:n.postalCode}}mapToLegacyBillingAddress(e){const{billingAddress:t,email:i,firstName:n,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:i,first_name:n,last_name:r,phone_number:o,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}getSessionId(e){return go(this,void 0,void 0,function*(){const{deviceData:t}=yield this.getDataCollector({riskCorrelationId:e});return t})}teardown(){return go(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 go(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 go(this,void 0,void 0,function*(){if(!this.venmoCheckout){const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadVenmoCheckout(),n=Object.assign({client:t,allowDesktop:!0,paymentMethodUsage:"multi_use"},e||{});this.venmoCheckout=yield new Promise((e,t)=>{i.create(n,(i,n)=>i?t(i):n.isBrowserSupported()?void e(n):t(new Pn))})}return this.venmoCheckout})}verifyCard(e,t,i){return go(this,void 0,void 0,function*(){const n=yield this.tokenizeCard(e,t);return this.challenge3DSVerification(n,i)})}tokenizeCard(e,t){return go(this,void 0,void 0,function*(){const{paymentData:i}=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}(i))throw new oo(["payment.paymentData"]);const n=this.getErrorsRequiredFields(i);if(!E(n))throw new ao(n);const r=this.mapToCreditCard(i,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 go(this,void 0,void 0,function*(){const i=yield this.get3DS();return this.present3DSChallenge(i,t,e)})}teardownModule(e){return e?e.teardown():Promise.resolve()}getClientTokenOrThrow(){if(!this.clientToken)throw new nn(Xi.PaymentNotInitialized);return this.clientToken}getErrorsRequiredFields(e){const{ccNumber:t,ccExpiry:i}=e,n={};return t||(n.ccNumber=[{message:"Credit card number is required",type:"required"}]),i||(n.ccExpiry=[{message:"Expiration date is required",type:"required"}]),n}mapToCreditCard(e,t){return{data:{creditCard:{cardholderName:e.ccName,number:e.ccNumber,cvv:e.ccCvv,expirationDate:`${e.ccExpiry.month}/${e.ccExpiry.year}`,options:{validate:!1},billingAddress:t&&{countryCodeAlpha2:t.countryCode,locality:t.city,countryName:t.country,postalCode:t.postalCode,streetAddress:t.address2?`${t.address1} ${t.address2}`:t.address1}}},endpoint:"payment_methods/credit_cards",method:"post"}}present3DSChallenge(e,t,i){const{nonce:n,bin:r}=i;if(!this.threeDSecureOptions||!n)throw new nn(Xi.PaymentNotInitialized);const{addFrame:o,removeFrame:a,challengeRequested:s=!0,additionalInformation:d}=this.threeDSecureOptions,c=()=>go(this,void 0,void 0,function*(){const t=yield e.cancelVerifyCard();return u.cancel(new Vn),t}),l=t.toFixed(2),u=new Pi(e.verifyCard({addFrame:(e,t)=>{o&&o(e,t,c)},amount:Number(l),bin:r,challengeRequested:s,nonce:n,removeFrame:a,onLookupComplete:(e,t)=>{t()},collectDeviceData:!0,additionalInformation:d}));return u.promise}}var fo=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class So{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return fo(this,void 0,void 0,function*(){const{braintreepaypal:t,methodId:i}=e,{container:n,onError:r}=t||{};if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(i),!o.clientToken)throw new Qi(Zi.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(i),o=a.getPaymentMethodOrThrow(i)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new Qi(Zi.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,i,Boolean(d.testMode),u)},e=>this.handleError(e,n,r))})}deinitialize(){return fo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return fo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return fo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,i,n,r){const{container:o,onClick:a=V}=t,{paypal:s}=this.braintreeHostWindow,d=null==s?void 0:s.FUNDING.PAYPAL;if(s&&d){const c=s.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(n),fundingSource:d,style:Object.assign(Object.assign({},r),{height:fr}),createOrder:()=>this.setupPayment(e,t,i),onApprove:n=>this.tokenizePayment(n,e,i,t),onClick:a});c.isEligible()&&c.render(`#${o}`)}else this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,i){var n;return fo(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(i),d=null==a?void 0:a.addresses[0],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===(n=s.initializationData)||void 0===n?void 0:n.intent})}catch(e){const{container:i,onError:n}=t;this.handleError(e,i,n)}})}tokenizePayment(e,t,i,n){return fo(this,void 0,void 0,function*(){try{const{deviceData:n}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:i,action:"set_external_checkout",nonce:a,device_data:n,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:i}=n;this.handleError(e,t,i)}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!zn(e))throw e;i(e)}}const wo=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t);return new So(e,Ee(),n,t)},[{id:"braintreepaypal"}]);var Io=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class _o{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return Io(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,methodId:i}=e,{container:n,onError:r}=t||{};if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.braintreepaypalcredit.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(i),!o.clientToken)throw new Qi(Zi.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(i),o=a.getPaymentMethodOrThrow(i)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new Qi(Zi.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,i,Boolean(d.testMode),Object.assign(Object.assign({},u),{height:fr}))},e=>this.handleError(e,n,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,i,n,r){const{container:o,onClick:a=V}=t,{paypal:s}=this.braintreeHostWindow;let d=!1;s&&[s.FUNDING.PAYLATER,s.FUNDING.CREDIT].forEach(c=>{if(!d){const l=s.Buttons({env:n?"sandbox":"production",fundingSource:c,style:r,createOrder:()=>this.setupPayment(e,t,i),onApprove:n=>this.tokenizePayment(n,e,i,t),onClick:a});l.isEligible()&&(l.render(`#${o}`),d=!0)}}),s&&d||this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,i){var n;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(i),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===(n=s.initializationData)||void 0===n?void 0:n.intent})}catch(e){const{container:i,onError:n}=t;this.handleError(e,i,n)}})}tokenizePayment(e,t,i,n){return Io(this,void 0,void 0,function*(){try{const{deviceData:n}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:i,action:"set_external_checkout",nonce:a,device_data:n,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:i}=n;this.handleError(e,t,i)}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!zn(e))throw e;i(e)}}const Co=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t);return new _o(e,Ee(),n,t)},[{id:"braintreepaypalcredit"}]);function bo(e){return"string"!=typeof e}function Po(e,t){if(t||e)return function(e){var t,i;const n={},r=H(e.root,bo),o=H(e.input,bo),a=H(e.toggle,bo),s=H(null===(t=e.text)||void 0===t?void 0:t.body,bo),d=H(null===(i=e.text)||void 0===i?void 0:i.caption,bo),c=e.branding;return Object.keys(r).length&&(n.root=r),Object.keys(o).length&&(n.input=o),Object.keys(a).length&&(n.toggle=a),Object.keys(s).length&&(n.text={},n.text.body=s),Object.keys(d).length&&(n.text=Object.assign({},n.text),n.text.caption=d),c&&(n.branding=c),n}(function(e,t){var i,n,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,w,I,_,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(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===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var Oo=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Eo{constructor(e,t){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.isAcceleratedCheckoutEnabled=!1}initialize({methodId:e,braintreefastlane:t}){var i;return Oo(this,void 0,void 0,function*(){if(!e)throw new gn('Unable to proceed because "methodId" argument is not provided.');const n=yield this.getValidPaymentMethodOrThrow(e),{isAcceleratedCheckoutEnabled:r,isFastlaneStylingEnabled:o}=n.initializationData||{},a=o?null===(i=n.initializationData)||void 0===i?void 0:i.fastlaneStyles:void 0;this.isAcceleratedCheckoutEnabled=!!r;try{if(this.isAcceleratedCheckoutEnabled){const e=Po(a,null==t?void 0:t.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(n.id,e)}}catch(e){}return Promise.resolve()})}deinitialize(){return Oo(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return Oo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Oo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return Oo(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:i}=e||{};if("function"!=typeof i)throw new gn('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');const n=this.paymentIntegrationService.getState().getCustomerOrThrow();if(this.isAcceleratedCheckoutEnabled&&n.isGuest){const e=yield this.shouldRunAuthenticationFlow();t&&"function"==typeof t&&t(),e&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(void 0,!0))}i()})}shouldRunAuthenticationFlow(){var e;return Oo(this,void 0,void 0,function*(){const t="braintreeacceleratedcheckout";try{yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t);return(null===(e=i.initializationData)||void 0===e?void 0:e.shouldRunAcceleratedCheckout)||!1}catch(e){return!1}})}getValidPaymentMethodOrThrow(e){return Oo(this,void 0,void 0,function*(){let t=e;try{yield this.paymentIntegrationService.loadPaymentMethod(t)}catch(i){t="braintree"===e?"braintreeacceleratedcheckout":"braintree",yield this.paymentIntegrationService.loadPaymentMethod(t)}return this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)})}}var Ao=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class To{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}getDeviceSessionId(){return Ao(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 Ao(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getCart(),{clientToken:r,config:o}=i.getPaymentMethodOrThrow(e);if(!r)throw new Qi(Zi.MissingPaymentMethod);this.methodId=e,this.braintreeIntegrationService.initialize(r),this.braintreeFastlane=yield this.braintreeIntegrationService.getBraintreeFastlane(null==n?void 0:n.id,o.testMode,t)})}getBraintreeFastlaneOrThrow(){if(!this.braintreeFastlane)throw new pn;return this.braintreeFastlane}getBraintreeFastlaneComponentOrThrow(){return this.getBraintreeFastlaneOrThrow().FastlaneCardComponent}runPayPalAuthenticationFlowOrThrow(e,t){var i;return Ao(this,void 0,void 0,function*(){try{const n=this.getMethodIdOrThrow(),r=this.getBraintreeFastlaneOrThrow(),{lookupCustomerByEmail:o,triggerAuthenticationFlow:a}=r.identity,s=this.paymentIntegrationService.getState(),d=s.getCartOrThrow(),c=s.getCustomer(),l=s.getBillingAddress(),{isFastlaneShippingOptionAutoSelectEnabled:u}=s.getPaymentMethodOrThrow(n).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:Tn.UNRECOGNIZED,addresses:[],instruments:[]}),void this.saveSessionIdToCookies(d.id);const{authenticationState:m,profileData:y}=yield a(p),g=(null===(i=null==y?void 0:y.shippingAddress)||void 0===i?void 0:i.phoneNumber)||"";if(m===Tn.CANCELED)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:[],instruments:[]}),void this.removeSessionIdFromCookies();const v=this.mapPayPalToBcAddress([y.shippingAddress],[g])||[],f=this.getPayPalBillingAddresses(y),S=f?this.mapPayPalToBcAddress([f],[g]):[],w=y.card?this.mapPayPalToBcInstrument(n,[y.card]):[],I=this.mergeShippingAndBillingAddresses(v,S);if(this.saveSessionIdToCookies(d.id),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:I,instruments:w}),S.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateBillingAddress(S[0])),S.length>0&&d.lineItems.digitalItems.length>0&&0===d.lineItems.physicalItems.length){const{firstName:e,lastName:t}=I[0],i=Object.assign(Object.assign({},S[0]),{firstName:e,lastName:t});yield this.paymentIntegrationService.updateBillingAddress(i)}v.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateShippingAddress(v[0]),t&&u&&(yield this.setShippingOption()))}catch(e){}})}getSessionIdFromCookies(){return Nr.get("bc-fastlane-sessionId")||""}saveSessionIdToCookies(e){const t=new Date;t.setDate(t.getDate()+14),Nr.set("bc-fastlane-sessionId",e,{expires:t,secure:!0})}removeSessionIdFromCookies(){Nr.remove("bc-fastlane-sessionId")}mapPayPalToBcInstrument(e,t){if(t)return t.map(t=>{const{id:i,paymentSource:n}=t,{brand:r,expiry:o,lastDigits:a,binDetails:s}=n.card,[d,c]=o.split("-");return{bigpayToken:i,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:_r.PAN}})}mapPayPalToBcAddress(e,t){if(!e)return[];const i=this.paymentIntegrationService.getState().getCountries()||[],n=e=>{const t=i.find(t=>t.code===e);return(null==t?void 0:t.name)||""};return e.map(e=>({id:Date.now(),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:n(e.countryCodeAlpha2),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:t&&t[0]||"",customFields:[]}))}getPayPalBillingAddresses(e){const{card:t,name:i}=e||{};if(!t)return;const{firstName:n,lastName:r}=t.paymentSource.card.billingAddress,{firstName:o,lastName:a}=i||{},{shippingAddress:s}=e||{},d=Object.assign(Object.assign({},t.paymentSource.card.billingAddress),{firstName:n||o,lastName:r||a});return s&&A(this.normalizeAddress(d),this.normalizeAddress(s))?s:d}normalizeAddress(e){return G(e,["id"])}mergeShippingAndBillingAddresses(e,t){const i=t.filter(t=>!e.some(e=>A(this.normalizeAddress(e),this.normalizeAddress(t))));return[...e,...i]}getMethodIdOrThrow(){if(!this.methodId)throw new gn('Unable to proceed because "methodId" argument is not provided.');return this.methodId}setShippingOption(){var e;return Ao(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getConsignments()||[],i=(null===(e=t[0])||void 0===e?void 0:e.availableShippingOptions)||[],n=i.find(e=>e.isRecommended);if(n||i.length){const e=n||i[0];yield this.paymentIntegrationService.selectShippingOption(e.id)}})}}const ko=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t),r=new To(e,n);return new Eo(e,r)},[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);var Do=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Mo{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i,this.buttonClassName="visa-checkout-wrapper",this.onError=V}initialize(e){return Do(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:i}=e;if(!i)throw new gn('Unable to proceed because "methodId" argument is not provided.');if(!t)throw new gn('Unable to proceed because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState(),r=n.getCheckoutOrThrow(),{clientToken:o,config:a}=n.getPaymentMethodOrThrow(i),s=n.getStoreConfigOrThrow();if(!o)throw new Qi(Zi.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||V;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 Do(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}signIn(){throw new vn('In order to sign in via VisaCheckout, the shopper must click on "Visa Checkout" button.')}signOut(e){return Do(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 Do(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(n),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e,t){const i=document.querySelector(`#${e}`);if(!i)throw new Error("Unable to proceed because the provided container ID is not valid.");return this.insertVisaCheckoutButton(i,t)}insertVisaCheckoutButton(e,t){const i=document.createElement("div");return i.style.display="flex",i.style.flexDirection="column",i.style.visibility="hidden",i.style.width="max-content",i.className=t,i.innerHTML='\n <img\n alt="Visa Checkout"\n class="v-button"\n role="button"\n src="https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178"\n />\n <a class="v-learn v-learn-default" style="text-align: right; display: block; font-size: 10px; color: #003366;" href="#" data-locale="en_US">Tell Me More</a>',e.appendChild(i),i}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const zo=Rt(e=>{const t=window,i=new bn(e),n=new Ln(new qn(a(),t,i));return new Mo(e,Ee(),n)},[{id:"braintreevisacheckout"}]);class No{constructor(e){if(!e)throw new Error("Currency settings missing");const{decimalPlaces:t,symbolLocation:i,symbol:n,thousandsSeparator:r,decimalSeparator:o}=e;if("string"!=typeof i||"string"!=typeof n||"string"!=typeof r||"string"!=typeof o||"string"!=typeof t)throw new gn("Invalid currency settings provided");this._decimalPlaces=parseInt(t,10),this._symbolLocation=i,this._symbol=n,this._thousandsSeparator=r,this._decimalSeparator=o}format(e){if("number"!=typeof e)throw new gn("Invalid amount provided");const t=this._formatNumber(e),i=this._formatCurrency(t);return e<0?`-${i}`:i}_formatNumber(e){const t=Math.abs(e),[i,n=""]=this._toFixed(t,this._decimalPlaces).split("."),r=i.replace(/\B(?=(\d{3})+(?!\d))/g,this._thousandsSeparator);return this._decimalPlaces<1?r:[r,n].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 xo=class{constructor(e){this._storeConfig=e,this._customerFormatter=new No(this._storeConfig.shopperCurrency),this._storeFormatter=new No(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};xo=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],xo);const Fo=xo,Ro=(e,t)=>!!e&&(!!e.lineItems.physicalItems.some(e=>e.isShippingRequired)||!(!t||!e.lineItems.customItems)&&e.lineItems.customItems.length>0);var Lo,Bo,jo,Uo,qo,Vo,Go,Ho,$o;function Wo(e){return e in Vo}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Lo||(Lo={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Bo||(Bo={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(jo||(jo={})),function(e){e.pill="pill",e.rect="rect"}(Uo||(Uo={})),function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(qo||(qo={})),function(e){e.AMEX="AMEX",e.DISCOVER="DISCOVER",e.INTERAC="INTERAC",e.JCB="JCB",e.MC="MASTERCARD",e.VISA="VISA"}(Vo||(Vo={})),function(e){e.OFFER="OFFER",e.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.SHIPPING_OPTION="SHIPPING_OPTION"}(Go||(Go={})),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"}(Ho||(Ho={})),function(e){e.INITIALIZE="INITIALIZE",e.SHIPPING_OPTION="SHIPPING_OPTION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.OFFER="OFFER"}($o||($o={}));var Yo,Ko=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Jo{constructor(e,t){this._gatewayIdentifier=e,this._paymentIntegrationService=t,this._isBuyNowFlow=!1,this._shouldRequestShipping=!0}mapToShippingAddressRequestBody({shippingAddress:e}){if(!e)return;const{company:t="",phone:i=""}=this._paymentIntegrationService.getState().getShippingAddress()||{};return this._mapToAddressRequestBody(e,t,i)}mapToBillingAddressRequestBody(e){const{billingAddress:t}=e.paymentMethodData.info;if(!t)return;const{company:i="",phone:n="",email:r,customFields:o=[]}=this._paymentIntegrationService.getState().getBillingAddress()||{};return Object.assign(Object.assign({},this._mapToAddressRequestBody(t,i,n,o)),{email:r||e.email})}mapToExternalCheckoutData(e){var t;const{paymentMethodData:{tokenizationData:{token:i},info:{cardNetwork:n,cardDetails:r}}}=e;if(!i)throw new Qi(Zi.MissingPaymentToken);return Promise.resolve(Object.assign({nonce:i,card_information:{type:n,number:r}},this._isBuyNowFlow&&{cart_id:null===(t=this._paymentIntegrationService.getState().getCart())||void 0===t?void 0:t.id}))}getRequiredData(){var e;return Ko(this,void 0,void 0,function*(){const t={emailRequired:!0};if(!this._isShippingAddressRequired())return t;const i=yield this._paymentIntegrationService.loadShippingCountries(),n=null===(e=i.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code);return Object.assign(Object.assign({},t),{shippingAddressRequired:!0,shippingAddressParameters:Object.assign({phoneNumberRequired:!0},n&&{allowedCountryCodes:n}),shippingOptionRequired:!0})})}getCallbackIntents(){return this._isShippingAddressRequired()?[Go.OFFER,Go.SHIPPING_ADDRESS,Go.SHIPPING_OPTION]:[Go.OFFER]}getCallbackTriggers(){return{availableTriggers:[$o.INITIALIZE,$o.SHIPPING_ADDRESS,$o.SHIPPING_OPTION,$o.OFFER],initializationTrigger:[$o.INITIALIZE],addressChangeTriggers:[$o.INITIALIZE,$o.SHIPPING_ADDRESS],shippingOptionsChangeTriggers:[$o.SHIPPING_OPTION],offerChangeTriggers:[$o.OFFER]}}getNonce(e){var t;const i=null===(t=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.nonce;if(!i)throw new Qi(Zi.MissingPaymentToken);return Promise.resolve(i)}extraPaymentData(){return Promise.resolve(void 0)}getMerchantInfo(){const{googleMerchantName:e,googleMerchantId:t,platformToken:i}=this.getGooglePayInitializationData();return{merchantName:e,merchantId:t,authJwt:i}}getTransactionInfo(){let e;if(this._isBuyNowFlow)e=this._getCurrencyCodeOrThrow();else{const{getCartOrThrow:t}=this._paymentIntegrationService.getState();e=t().currency.code}const t=this.getGooglePayInitializationData().storeCountry;return Object.assign(Object.assign({},t&&{countryCode:t}),{currencyCode:e,totalPriceStatus:qo.ESTIMATED,totalPrice:"0"})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData().gatewayMerchantId;if(!e)throw new gn("Unable to proceed, gatewayMerchantId is missing.");return{gateway:this._gatewayIdentifier,gatewayMerchantId:e}}getCardParameters(){return{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.getPaymentMethod().supportedCards.filter(Wo).map(e=>Vo[e]),billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!0}}}initialize(e,t,i){return this._getPaymentMethodFn=e,this._isBuyNowFlow=Boolean(t),this._currencyCode=i,this._isBuyNowFlow&&this._getCurrencyCodeOrThrow(),Promise.resolve()}handleShippingAddressChange(e){var t,i,n,r;return Ko(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 Fo(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===(i=d.selectedShippingOption)||void 0===i?void 0:i.id)||(null==u?void 0:u.id)||(null===(n=l[0])||void 0===n?void 0:n.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 Ko(this,void 0,void 0,function*(){if("shipping_option_unselected"!==e)return this._paymentIntegrationService.selectShippingOption(e)})}getTotalPrice(){const{getCheckoutOrThrow:e,getCartOrThrow:t}=this._paymentIntegrationService.getState(),{decimalPlaces:i}=t().currency;return J(e().outstandingBalance,i).toFixed(i)}handleCoupons(e){return Ko(this,void 0,void 0,function*(){const{redemptionCodes:t=[]}=e,{offers:i}=this.getAppliedCoupons();let n;return yield t.reduce((e,t)=>Ko(this,void 0,void 0,function*(){if(yield e,i.some(({redemptionCode:e})=>e===t))return;const r=yield this.applyCoupon(t);r&&(n=r)}),Promise.resolve()),yield i.reduce((e,i)=>Ko(this,void 0,void 0,function*(){yield e,t.includes(i.redemptionCode)||(yield this._paymentIntegrationService.removeCoupon(i.redemptionCode))}),Promise.resolve()),{newOfferInfo:this.getAppliedCoupons(),error:n}})}getAppliedCoupons(){const e=this._paymentIntegrationService.getState(),{coupons:t}=e.getCheckout()||{};return{offers:(t||[]).map(e=>{const{displayName:t,code:i}=e;return{redemptionCode:i,description:t}})}}applyCoupon(e){return Ko(this,void 0,void 0,function*(){let t;try{yield this._paymentIntegrationService.applyCoupon(e)}catch(e){return e instanceof Error&&(t={reason:Ho.OFFER_INVALID,message:e.message,intent:$o.OFFER}),t}})}setShouldRequestShipping(e){this._shouldRequestShipping=e}getGooglePayInitializationData(){return tn(this.getPaymentMethod().initializationData,()=>new gn("Missing initialization data."))}getPaymentMethod(){return tn(this._getPaymentMethodFn,()=>new nn(Xi.PaymentNotInitialized))()}getGatewayIdentifier(){return this._gatewayIdentifier}setGatewayIdentifier(e){this._gatewayIdentifier=e||this.getGatewayIdentifier()}_isShippingAddressRequired(){const{getCartOrThrow:e,getStoreConfigOrThrow:t,getShippingAddress:i}=this._paymentIntegrationService.getState(),n=t();let r;return r=Wt(n.checkoutSettings.features,"PI-4290.google_pay_require_shipping_address")?this._shouldRequestShipping:void 0===i(),r&&Ro(e(),n)}_mapToAddressRequestBody(e,t,i,n){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||i,customFields:n||[]}}_getFirstAndLastName(e){const t=e.split(" ");return 1===t.length?[e,""]:[t.slice(0,-1).join(" "),t[t.length-1]]}_getCurrencyCodeOrThrow(){return tn(this._currencyCode,()=>new gn('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}_getGooglePayShippingOption({id:e,cost:t,description:i,additionalDescription:n}){var r;const o=null===(r=this._currencyService)||void 0===r?void 0:r.toCustomerCurrency(t);return this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features["PI-3540.googlepay_new_shipping_options_description"]?{id:e,label:`${o||t} ${i}`,description:n}:{id:e,label:i,description:o||t}}}function Zo(e){return"object"==typeof e&&null!==e&&"statusCode"in e}function Xo(e){return Object.values(Yo).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"}(Yo||(Yo={}));var Qo=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ea{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t;return Qo(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!Xo(e.methodId))throw new gn('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!i)throw new gn("Unable to proceed without valid options.");let n,r=this._paymentIntegrationService.getState();try{n=r.getPaymentMethodOrThrow(this._getMethodId())}catch(e){r=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),n=r.getPaymentMethodOrThrow(this._getMethodId())}try{yield this._googlePayPaymentProcessor.initialize(()=>n,this._getGooglePayClientOptions(null===(t=n.initializationData)||void 0===t?void 0:t.storeCountry))}catch(e){return}this._addPaymentButton(i)})}signIn(){return Promise.reject(new vn('In order to sign in via Google Pay, the shopper must click on "Google Pay" button.'))}signOut(){var e;return Qo(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{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,shippingAddress:i,shippingOptionData:n,offerData:r})=>Qo(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(i):void 0;s.includes(t)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(n.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:qo.FINAL,totalPrice:p})},c&&{newShippingOptionParameters:c}),l&&{newOfferInfo:l}),h&&{error:h})})}}}_addPaymentButton({container:e,buttonColor:t,buttonType:i,onClick:n,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!=i?i:"plain",onClick:this._handleClick(r,n)})}_handleClick(e,t){return i=>Qo(this,void 0,void 0,function*(){i.preventDefault(),t&&"function"==typeof t&&t();try{yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let i=t;if(Zo(t)){if("CANCELED"===t.statusCode)throw new Vn;i=new Kr(JSON.stringify(t))}throw null==e||e(new Kr("An error occurred while requesting your Google Pay payment details.")),i}})}_interactWithPaymentSheet(){return Qo(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e),i=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(e),n="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;t&&(yield this._paymentIntegrationService.updateBillingAddress(t)),i&&(yield this._paymentIntegrationService.updateShippingAddress(i)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodId(),e,n)})}_getMethodId(){return tn(this._methodId,()=>new nn(Xi.PaymentNotInitialized))}}var ta=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ia{constructor(e,t,i,n){this._scriptLoader=e,this._gateway=t,this._requestSender=i,this._formPoster=n,this._baseRequest={apiVersion:2,apiVersionMinor:0}}initialize(e,t,i,n){return ta(this,void 0,void 0,function*(){this._paymentsClient=yield this._scriptLoader.getGooglePaymentsClient(e().config.testMode,t),yield this._gateway.initialize(e,i,n),this._buildButtonPayloads()})}initializeWidget(){return ta(this,void 0,void 0,function*(){yield this._buildWidgetPayloads(),yield this._determineReadinessToPay(),this._prefetchGooglePaymentData()})}getNonce(e){return this._gateway.getNonce(e)}extraPaymentData(){return ta(this,void 0,void 0,function*(){return this._gateway.extraPaymentData()})}addPaymentButton(e,t){const i=document.querySelector(`#${e}`);if(!i)return;const n=this._getPaymentsClient().createButton(Object.assign(Object.assign({},t),{allowedPaymentMethods:[this._getBaseCardPaymentMethod()]}));return i.appendChild(n)}showPaymentSheet(){return ta(this,void 0,void 0,function*(){const e=this._getPaymentDataRequest();return this._getPaymentsClient().loadPaymentData(e)})}setExternalCheckoutXhr(e,t){return ta(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t)})}setExternalCheckoutForm(e,t,i){return ta(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t,!0,i)})}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 ta(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 ta(this,void 0,void 0,function*(){return this._gateway.handleShippingAddressChange(e)})}handleShippingOptionChange(e){return ta(this,void 0,void 0,function*(){yield this._gateway.handleShippingOptionChange(e)})}handleCoupons(e){return ta(this,void 0,void 0,function*(){return this._gateway.handleCoupons(e)})}getTotalPrice(){return this._gateway.getTotalPrice()}_setExternalCheckout(e,t,i=!1,n){return ta(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(i)return new Promise(e=>{this._formPoster.postForm(n?`${n}/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"},hr),body:o})})}_prefetchGooglePaymentData(){const e=this._getPaymentDataRequest();e.transactionInfo=this._gateway.getTransactionInfo(),this._getPaymentsClient().prefetchPaymentData(e)}_determineReadinessToPay(){return ta(this,void 0,void 0,function*(){try{const{result:e}=yield this._getPaymentsClient().isReadyToPay(this._getIsReadyToPayRequest());if(!1===e)throw new Kr("Google Pay is not supported by the current device and browser, please try another payment method.")}catch(e){if(e instanceof Kr)throw e;throw new Kr}})}_buildButtonPayloads(){this._baseCardPaymentMethod={type:"CARD",parameters:this._gateway.getCardParameters()}}_buildWidgetPayloads(){return ta(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()}}),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()),{callbackIntents:this._gateway.getCallbackIntents(),offerInfo:this._gateway.getAppliedCoupons()}),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 tn(e,()=>new nn(Xi.PaymentNotInitialized))}}class na{constructor(e){this._scriptLoader=e,this._window=window}getGooglePaymentsClient(e=!1,t){return i=this,n=void 0,o=function*(){if(yield this._scriptLoader.loadScript("https://pay.google.com/gp/p/js/pay.js"),!this._window.google)throw new pn;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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}function ra(){return new na(a())}const oa=Rt(e=>{const t=i();return new ea(e,new ia(ra(),new Jo("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),aa=Rt(e=>{const t=i();return new ea(e,new ia(ra(),new Jo("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]);class sa extends Jo{constructor(e){super("authorizenet",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return i=this,n=void 0,o=function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return function(e){if(!function(e){return"paymentGatewayId"in e}(e))throw new Qi(Zi.MissingPaymentMethod)}(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.paymentGatewayId}}}const da=Rt(e=>new ea(e,new ia(ra(),new sa(e),i(),Ee())),[{id:"googlepayauthorizenet"}]),ca=e=>"object"==typeof e&&null!==e&&"body"in e;function la(e){if(!function(e){return"checkoutcomkey"in e}(e))throw new Qi(Zi.MissingPaymentMethod)}var ua=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ha extends Jo{constructor(e,t){super("checkoutltd",e),this._requestSender=t}processAdditionalAction(e){return new Promise((t,i)=>{if(ca(e)&&function(e){var t;if("object"!=typeof e||null===e)return!1;const i=e;return"string"==typeof(null===(t=i.three_ds_result)||void 0===t?void 0:t.acs_url)&&"string"==typeof i.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);i(e)})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ua(this,void 0,void 0,function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);let n;try{n=JSON.parse(i.nonce)}catch(e){throw new gn("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 Qi(Zi.MissingPaymentToken)}(n),i.nonce=yield this._tokenize(n),i})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return la(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.checkoutcomkey}}_tokenize(e){return ua(this,void 0,void 0,function*(){const t=this.getPaymentMethod().config.testMode?"https://api.sandbox.checkout.com/tokens":"https://api.checkout.com/tokens",i=this.getGooglePayInitializationData();la(i);const{body:n}=yield this._requestSender.post(t,{credentials:!1,body:{type:"googlepay",token_data:e},headers:{Authorization:i.checkoutcomkey,"Content-Type":ur.Json,"X-XSRF-TOKEN":null}});return n.token})}}const pa=Rt(e=>{const t=i();return new ea(e,new ia(ra(),new ha(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]);class ma extends Jo{constructor(e){super("cybersource",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return i=this,n=void 0,o=function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}const ya=Rt(e=>new ea(e,new ia(ra(),new ma(e),i(),Ee())),[{id:"googlepaycybersourcev2"}]),ga=Rt(e=>new ea(e,new ia(ra(),new ma(e),i(),Ee())),[{id:"googlepaybnz"}]);class va extends Jo{constructor(e){super("chase",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return i=this,n=void 0,o=function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}const fa=Rt(e=>new ea(e,new ia(ra(),new va(e),i(),Ee())),[{id:"googlepayorbital"}]);var Sa,wa,Ia,_a,Ca,ba,Pa,Oa,Ea,Aa;!function(e){e.SHIPPING="shipping",e.BILLING="billing"}(Sa||(Sa={})),function(e){e.SPLIT="split",e.FULL="full",e.ORGANIZATION="organization"}(wa||(wa={})),function(e){e.SUCCESS="success",e.ERROR="error"}(Ia||(Ia={})),function(e){e.CreditCard="card",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"}(_a||(_a={})),function(e){e.NEVER="never",e.AUTO="auto",e.ALWAYS="always",e.PAYMENT="payment",e.IF_REQUIRED="if_required"}(Ca||(Ca={})),function(e){e.V3="v3",e.ACACIA="acacia",e.BASIL="basil",e.CLOVER="clover"}(ba||(ba={})),function(e){e.PAYMENT="payment",e.AUTHENTICATION="linkAuthentication",e.SHIPPING="address",e.EXPRESS_CHECKOUT="expressCheckout"}(Pa||(Pa={})),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"}(Oa||(Oa={})),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"}(Ea||(Ea={})),function(e){e.ON_SESSION="on_session",e.OFF_SESSION="off_session"}(Aa||(Aa={}));var Ta=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ka{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}getStripeClient(e,t,i,n,r){return Ta(this,void 0,void 0,function*(){if(this.stripeWindow.bcStripeClient)return this.stripeWindow.bcStripeClient;const o=yield this.load(i),{stripePublishableKey:a,stripeConnectedAccount:s}=e,d=o(a,Object.assign(Object.assign(Object.assign(Object.assign({},s?{stripeAccount:s}:{}),t?{locale:t}:{}),n?{betas:n}:{}),r?{apiVersion:r}:{}));return Object.assign(this.stripeWindow,{bcStripeClient:d}),d})}getElements(e,t){return Ta(this,void 0,void 0,function*(){let i=this.stripeWindow.bcStripeElements;return i?yield this.updateStripeElements(t):(i=e.elements(t),Object.assign(this.stripeWindow,{bcStripeElements:i})),i})}updateStripeElements(e){return Ta(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeElements;t&&(t.update(e),yield t.fetchUpdates())})}getCheckoutSession(e,t){return Ta(this,void 0,void 0,function*(){let i=this.stripeWindow.bcStripeCheckoutSession;return i||(i=yield e.initCheckout(t),Object.assign(this.stripeWindow,{bcStripeCheckoutSession:i})),i})}load(e){return Ta(this,void 0,void 0,function*(){if(!this.stripeWindow.Stripe&&(yield this.scriptLoader.loadScript(this.getScriptUrl(e)),!this.stripeWindow.Stripe))throw new pn;return this.stripeWindow.Stripe})}getScriptUrl(e){return e&&e!==ba.V3?`https://js.stripe.com/${e}/stripe.js`:"https://js.stripe.com/v3/"}}const Da=["payment_element_beta_2","alipay_pm_beta_1","link_default_integration_beta_1","shipping_address_element_beta_1","address_element_beta_1"],Ma="2020-03-02;alipay_beta=v1;link_beta=v1";function za(e){if(!function(e){return"stripeConnectedAccount"in e&&"stripePublishableKey"in e&&"stripeVersion"in e}(e))throw new Qi(Zi.MissingPaymentMethod)}var Na=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class xa extends Jo{constructor(e,t){super("stripe",e),this.paymentIntegrationService=e,this.scriptLoader=t}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return Na(this,void 0,void 0,function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);let n;try{n=JSON.parse(i.nonce)}catch(e){throw new gn("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 Qi(Zi.MissingPaymentToken)}(n),i.nonce=n.id,i})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();za(e);const{stripeVersion:t,stripePublishableKey:i,stripeConnectedAccount:n}=e;return{gateway:this.getGatewayIdentifier(),"stripe:version":t,"stripe:publishableKey":`${i}/${n}`}}processAdditionalAction(e,t){var i;return Na(this,void 0,void 0,function*(){if(!t)throw new oo(["payment"]);if(!ca(e)||("object"!=typeof(n=e.body)||null===n||!("three_ds_result"in n)||!("errors"in n)))throw e;var n;if(Z(e.body.errors,{code:"three_d_secure_required"})){const n=this.getGooglePayInitializationData();za(n),this.stripeUPEClient=yield this.loadStripeJs(n,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 Vn;throw new Kr}if(!(null==o?void 0:o.paymentIntent)&&!a)throw new Qn;return this.paymentIntegrationService.submitPayment({methodId:t,paymentData:{nonce:(null===(i=null==o?void 0:o.paymentIntent)||void 0===i?void 0:i.id)||r}})}throw e})}loadStripeJs(e,t){return Na(this,void 0,void 0,function*(){if(this.stripeUPEClient)return this.stripeUPEClient;const i=this.paymentIntegrationService.getState().getCartLocale();return"googlepaystripeocs"===t&&e.useNewStripeJsVersion?this.scriptLoader.getStripeClient(e,i,ba.CLOVER):this.scriptLoader.getStripeClient(e,i,ba.V3,Da,Ma)})}_isCancellationError(e){var t,i;return e&&-1!==(null===(i=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===i?void 0:i.indexOf("canceled"))}_throwDisplayableStripeError(e){if(P(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}}const Fa=Rt(e=>new ea(e,new ia(ra(),new xa(e,new ka(a())),i(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeocs"}]),Ra=Rt(e=>new ea(e,new ia(ra(),new xa(e,new ka(a())),i(),Ee())),[{id:"googlepaystripeupe"}]);class La extends Jo{constructor(e){super("worldpay",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return i=this,n=void 0,o=function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}const Ba=Rt(e=>new ea(e,new ia(ra(),new La(e),i(),Ee())),[{id:"googlepayworldpayaccess"}]);var ja=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ua extends Jo{constructor(e,t){super("braintree",e),this._braintreeSdk=t,this._methodId=Yo.BRAINTREE,this._service=e}initialize(e,t,i){const n=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return ja(this,void 0,void 0,function*(){yield n.initialize.call(this,e,t,i);let r=n.getPaymentMethod.call(this);if(r.clientToken||(r=(yield this._service.loadPaymentMethod(this._methodId)).getPaymentMethodOrThrow(this._methodId)),!r.clientToken||!r.initializationData)throw new Qi(Zi.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 i;return ja(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),{clientToken:r,initializationData:o}=t.getPaymentMethod.call(this);if(!r||!o||!(null===(i=o.card_information)||void 0===i?void 0:i.bin))throw new Qi(Zi.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,n,s)).nonce}return n})}extraPaymentData(){return ja(this,void 0,void 0,function*(){return{deviceSessionId:yield this._getBraintreeDeviceData()}})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ja(this,void 0,void 0,function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);let n;try{n=JSON.parse(i.nonce)}catch(e){throw new gn("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 Qi(Zi.MissingPaymentToken)}(n),i.nonce=n.androidPayCards[0].nonce,i.card_information.bin=n.androidPayCards[0].details.bin,i.card_information.isNetworkTokenized=n.androidPayCards[0].details.isNetworkTokenized,i})}getCardParameters(){return super.getCardParameters()}getPaymentGatewayParameters(){const e=Object.create(null,{getMerchantInfo:{get:()=>super.getMerchantInfo},getTransactionInfo:{get:()=>super.getTransactionInfo},getRequiredData:{get:()=>super.getRequiredData}});return ja(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 Qi(Zi.MissingPaymentMethod);return this._braintreeGooglePayment}_getBraintreeDeviceData(){return ja(this,void 0,void 0,function*(){const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e})}_braintreePresent3DSChallenge(e,t,i,n){return new Pi(e.verifyCard({amount:t,bin:n,nonce:i,onLookupComplete:(e,t)=>{t()}})).promise}}const qa=Rt(e=>{const t=i(),n=window,r=new bn(e),o=new Ln(new qn(a(),n,r));return new ea(e,new ia(ra(),new Ua(e,o),t,Ee()))},[{id:"googlepaybraintree"}]);var Va=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ga{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,i){return Va(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const n=this.getPayPalFastlaneSdkConfiguration(e,t,i);if(yield this.loadPayPalSdk(n),!this.window.paypalFastlaneSdk)throw new pn}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,i,n){return Va(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||n){const n=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i);yield this.loadPayPalSdk(n)}if(!this.window.paypalGooglePay)throw new pn;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t){return Va(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new pn}return this.window.paypalApms})}getPayPalMessages(e,t){return Va(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new pn;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Va(this,void 0,void 0,function*(){const i=this.transformConfig(e),n=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(i).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:n})})}getPayPalFastlaneSdkConfiguration(e,t,i){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,attributionId:d}=r;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t,intent:o},attributes:{"data-client-metadata-id":i.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":n}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i=!0){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||i;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":n,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:n,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=i,u=l,h=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:n},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{clientId:n,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=i;return{options:Object.assign({"client-id":n,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":o}}}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}function Ha(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 Qi(Zi.MissingPaymentMethod)}var $a=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Wa extends Jo{constructor(e,t){super("paypalsb",e),this.payPalCommerceSdk=t,this.service=e}initialize(e,t,i){const n=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return $a(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:i;if(!c)throw new Qi(Zi.MissingPaymentMethod);yield n.initialize.call(this,e,t,c);const l=n.getPaymentMethod.call(this);if(!l.initializationData)throw new Qi(Zi.MissingPaymentMethod);Ha(l);const u=yield this.payPalCommerceSdk.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 $a(this,void 0,void 0,function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),i})}}const Ya=Rt(e=>new ea(e,new ia(ra(),new Wa(e,new Ga(a())),i(),Ee())),[{id:"googlepaypaypalcommerce"}]);var Ka=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ja extends Jo{constructor(e,t){super("googlepay_bigcommerce_payments",e),this.payPalSdkHelper=t,this.service=e}initialize(e,t,i){const n=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return Ka(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:i;if(!c)throw new Qi(Zi.MissingPaymentMethod);yield n.initialize.call(this,e,t,c);const l=n.getPaymentMethod.call(this);if(!l.initializationData)throw new Qi(Zi.MissingPaymentMethod);Ha(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 Ka(this,void 0,void 0,function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),i})}}const Za=Rt(e=>new ea(e,new ia(ra(),new Ja(e,new Mr(a())),i(),Ee())),[{id:"googlepay_bigcommerce_payments"}]);function Xa(){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 Qa=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class es extends Jo{constructor(e,t){super("worldlinena",e),this.formPoster=t}extraPaymentData(){return Qa(this,void 0,void 0,function*(){return Promise.resolve({browser_info:Xa()})})}processAdditionalAction(e){return Qa(this,void 0,void 0,function*(){if(!function(e){return ca(e)&&(t=e.body,D(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&O(t.errors)&&Z(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:i,payer_auth_request:n,merchant_data:r}=t||{};if(!i||!n||!r)throw new oo(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(i,{threeDSSessionData:n,creq:r},e,"_top")})})}}const ts=Rt(e=>new ea(e,new ia(ra(),new es(e,Ee()),i(),Ee())),[{id:"googlepaytdonlinemart"}]);var is,ns,rs,os,as,ss,ds;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(is||(is={})),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"}(os||(os={})),function(e){e.pill="pill",e.rect="rect"}(as||(as={})),(ss||(ss={})).OXXO="oxxo",function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(ds||(ds={}));var cs=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ls{constructor(e,t,i,n){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=i,this.paypalCommerceScriptLoader=n}loadPayPalSdk(e,t,i,n){return cs(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,i,n),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new pn;return this.paypalSdk}createBuyNowCartOrThrow(e){return cs(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new Zn}})}createOrder(e,t){return cs(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:i},t));return n})}createOrderCardFields(e,t){return cs(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n,setupToken:r}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:i},t));return Object.assign({orderId:n},r?{setupToken:r}:{})})}updateOrder(){return cs(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getConsignmentsOrThrow()[0];try{yield this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:i.availableShippingOptions,cartId:t.id,selectedShippingOption:i.selectedShippingOption})}catch(e){throw new Qn}})}getOrderStatus(e,t){return cs(this,void 0,void 0,function*(){try{const{status:i}=yield this.paypalCommerceRequestSender.getOrderStatus(e,t);return i}catch(e){throw new Qn}})}tokenizePayment(e,t){const i=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new Qi(Zi.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},i.source===kt.BuyNow&&{cart_id:i.id}))}submitPayment(e,t,i){return cs(this,void 0,void 0,function*(){const n={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:n},i?{gatewayId:i}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],i=t.availableShippingOptions||[],n=i.find(e=>e.isRecommended),r=(e?i.find(t=>t.id===e):i.find(e=>{var i;return e.id===(null===(i=t.selectedShippingOption)||void 0===i?void 0:i.id)}))||n||i[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,i;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===(i=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===i?void 0:i.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:i}=e,{address:n,name:{full_name:r}}=i[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:n.address_line_1,address2:n.address_line_2,city:n.admin_area_2,countryCode:n.country_code,postalCode:n.postal_code,stateOrProvinceCode:n.admin_area_1})}getValidButtonStyle(e){const{color:t,height:i,label:n,shape:r}=e||{},o={color:t&&os[t]?t:void 0,height:this.getValidHeight(i),label:n&&rs[n]?n:void 0,shape:r&&as[r]?r:void 0};return H(o,k)}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 us=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class hs{constructor(e){this.requestSender=e}createOrder(e,t){return us(this,void 0,void 0,function*(){const i=`/api/storefront/payment/${e}`,n=t,r=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.post(i,{headers:r,body:n})).body})}updateOrder(e){return us(this,void 0,void 0,function*(){const t=e,i=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:i,body:t})).body})}getOrderStatus(e="paypalcommerce",t){return us(this,void 0,void 0,function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body})}}var ps=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ms{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,i,n){return ps(this,void 0,void 0,function*(){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,i);return this.loadPayPalSDK(r,n)})}loadPayPalSDK(e,t=!1){return ps(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),i=this.transformConfig(e.attributes),n=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(n,{async:!0,attributes:i})}if(!this.window.paypal)throw new pn;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,i=!0){const{id:n,clientToken:r,initializationData:o}=e;if(!(null==o?void 0:o.clientId))throw new Qi(Zi.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:v}=o,f=h||i,S="paypalcommercecreditcards"===n,w=S?["card"]:[],I=p?["credit","paylater"]:[],_=u?["venmo"]:[],C=v?["googlepay"]:[],b=i?["card-fields"]:[],P=[...S?[]:["card"],...p?[]:["credit","paylater"],...u?[]:["venmo"],...y.filter(e=>!g.includes(e))],O=[...w,...I,..._,...g];return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":O.length>0?O:void 0,"disable-funding":P.length>0?P:void 0,commit:f,components:["buttons","hosted-fields","payment-fields","legal",...C,...b],currency:t,intent:a},m&&{"buyer-country":c}),attributes:{"data-partner-attribution-id":l,"data-client-token":r}}}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}const ys=e=>{const{getHost:t}=e.getState();return new ls(Ee(),e,new hs(i({host:t()})),new ms(a()))};var gs=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class vs{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=V}initialize(e){return gs(this,void 0,void 0,function*(){const{paypalcommerce:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.paypalcommerce.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.paypalcommerce.onClick" argument is not a function.');this.onError=t.onError||V,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.paypalCommerceIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 gs(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return gs(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 i,n;const{container:r,onClick:o,onComplete:a}=t,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:c,paymentButtonStyles:l,isAppSwitchEnabled:u}=d.initializationData||{},{checkoutTopButtonStyles:h}=l||{},p=Object.assign(Object.assign(Object.assign({},this.isPaypalCommerceAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommerce"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)}),o&&{onClick:()=>o()}),m=Object.assign(Object.assign({},!u&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,i)=>this.onHostedCheckoutApprove(t,i,e,a)}),y=Object.assign(Object.assign({fundingSource:s.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},h),{height:fr}))},p),c&&m),g=s.Buttons(y);g.isEligible()?(null===(i=g.hasReturned)||void 0===i?void 0:i.call(g))&&this.isPaypalCommerceAppSwitchEnabled(e)?null===(n=g.resume)||void 0===n||n.call(g):g.render(`#${r}`):this.paypalCommerceIntegrationService.removeElement(r)}onHostedCheckoutApprove(e,t,i,n){return gs(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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:i}}),yield this.paypalCommerceIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return gs(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 gs(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)}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}}const fs=Rt(e=>new vs(e,ys(e)),[{id:"paypalcommerce"}]);var Ss=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ws{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=V}initialize(e){return Ss(this,void 0,void 0,function*(){const{paypalcommercecredit:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.paypalcommercecredit.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.paypalcommercecredit.onClick" argument is not a function.');this.onError=t.onError||V,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.paypalCommerceIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 Ss(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Ss(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:i,onComplete:n,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,i)=>this.onHostedCheckoutApprove(t,i,e,n)}),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:fr}))},u),s&&h),n=o.Buttons(t);n.isEligible()&&(n.render(`#${i}`),m=!0)}}),m||this.paypalCommerceIntegrationService.removeElement(i)}onHostedCheckoutApprove(e,t,i,n){return Ss(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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:i}}),yield this.paypalCommerceIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ss(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 Ss(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 Is=Rt(e=>new ws(e,ys(e)),[{id:"paypalcommercecredit"}]);var _s=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Cs{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return _s(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.paypalCommerceIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 _s(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return _s(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:i,onClick:n}=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:fr})),createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},n&&{onClick:()=>n()}),c=r.Buttons(d);c.isEligible()?c.render(`#${i}`):this.paypalCommerceIntegrationService.removeElement(i)}}const bs=Rt(e=>new Cs(e,ys(e)),[{id:"paypalcommercevenmo"}]);var Ps,Os,Es,As,Ts,ks,Ds,Ms,zs,Ns,xs=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Fs{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,i,n){return xs(this,void 0,void 0,function*(){if(!this.window.paypal||n){const n=this.getPayPalSdkScriptConfigOrThrow(e,t,i);if(yield this.loadPayPalSdk(n),!this.window.paypal)throw new pn}return this.window.paypal})}getPayPalFastlaneSdk(e,t,i){return xs(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const n=this.getPayPalFastlaneSdkConfiguration(e,t,i);if(yield this.loadPayPalSdk(n),!this.window.paypalFastlaneSdk)throw new pn}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,i,n){return xs(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||n){const n=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i);yield this.loadPayPalSdk(n)}if(!this.window.paypalGooglePay)throw new pn;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t){return xs(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new pn}return this.window.paypalApms})}getPayPalMessages(e,t){return xs(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new pn;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return xs(this,void 0,void 0,function*(){const i=this.transformConfig(e),n=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(i).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:n})})}getPayPalSdkScriptConfigOrThrow(e,t,i=!0){const{id:n,clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new Qi(Zi.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:v}=o,f=h||i,S="paypalcommercecreditcards"===n||"bigcommerce_payments_creditcards"===n,w=S?["card"]:[],I=p?["credit","paylater"]:[],_=u?["venmo"]:[],C=v?["googlepay"]:[],b=i?["card-fields"]:[],P=[...S?[]:["card"],...p?[]:["credit","paylater"],...u?[]:["venmo"],...y.filter(e=>!g.includes(e))],O=[...w,...I,..._,...g];return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":O.length>0?O:void 0,"disable-funding":P.length>0?P:void 0,commit:f,components:["buttons","hosted-fields","payment-fields","legal",...C,...b],currency:t,intent:a},m&&{"buyer-country":c}),attributes:{"data-partner-attribution-id":l,"data-client-token":r}}}getPayPalFastlaneSdkConfiguration(e,t,i){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,attributionId:d}=r;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t,intent:o},attributes:{"data-client-metadata-id":i.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":n}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i=!0){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||i;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":n,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:n,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=i,u=l,h=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:n},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{clientId:n,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=i;return{options:Object.assign({"client-id":n,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":o}}}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}function Rs(){return new Fs(o())}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Ps||(Ps={})),(Os||(Os={})).Always="SCA_ALWAYS",function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(Es||(Es={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(As||(As={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Ts||(Ts={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(ks||(ks={})),function(e){e.pill="pill",e.rect="rect"}(Ds||(Ds={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(Ms||(Ms={})),(zs||(zs={})).OXXO="oxxo",function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(Ns||(Ns={}));var Ls=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Bs{constructor(){this.window=window}initializePayPalFastlane(e,t,i){return Ls(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:i||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new pn;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return Ls(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return Ls(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 i={expires:t,secure:!0};Nr.set("bc-fastlane-sessionId",e,i)}removeStorageSessionId(){Nr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Nr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var i,n,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(n=null===(i=null==a?void 0:a.card)||void 0===i?void 0:i.paymentSource)||void 0===n?void 0:n.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||Ms.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:i,paymentSource:n}=t,{brand:r,expiry:o,lastDigits:a}=n.card,[s,d]=o.split("-");return[{bigpayToken:i,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:_r.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,i,n){const[r,o]=t.fullName.split(" "),a=(null==i?void 0:i.nationalNumber)||"",s=(null==i?void 0:i.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:n||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return A(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return G(e,["id","phone"])}}function js(){return new Bs}function Us(e){return"string"!=typeof e}function qs(e,t){if(t||e)return function(e){var t,i;const n={},r=H(e.root,Us),o=H(e.input,Us),a=H(e.toggle,Us),s=H(null===(t=e.text)||void 0===t?void 0:t.body,Us),d=H(null===(i=e.text)||void 0===i?void 0:i.caption,Us),c=e.branding;return Object.keys(r).length&&(n.root=r),Object.keys(o).length&&(n.input=o),Object.keys(a).length&&(n.toggle=a),Object.keys(s).length&&(n.text={},n.text.body=s),Object.keys(d).length&&(n.text=Object.assign({},n.text),n.text.caption=d),c&&(n.branding=c),n}(function(e,t){var i,n,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,w,I,_,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(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===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var Vs=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Gs{constructor(e,t,i){this.paymentIntegrationService=e,this.paypalSdkScriptLoader=t,this.paypalFastlaneUtils=i}initialize(e){var t;return Vs(this,void 0,void 0,function*(){const{methodId:i,paypalcommercefastlane:n}=e;if(!i)throw new gn('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(i);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(i),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(o,r.currency.code,r.id);yield this.paypalFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(i,n))}catch(e){}return Promise.resolve()})}deinitialize(){return Vs(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return Vs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Vs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return Vs(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:i,methodId:n}=e||{};if(!n)throw new gn('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof i)throw new gn('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(n)}catch(e){}}i()})}runPayPalAuthenticationFlowOrThrow(e){return Vs(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow().id,n=t.getCustomer(),r=t.getBillingAddress(),o=(null==n?void 0:n.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.paypalFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===Ms.CANCELED;yield this.updateCustomerDataState(e,s),d?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(i)})}updateCustomerDataState(e,t){var i;return Vs(this,void 0,void 0,function*(){const n=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&&n.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),n=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=n.initializationData||{},o=t.getConsignments()||[],a=(null===(i=o[0])||void 0===i?void 0:i.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 i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:n,isFastlaneStylingEnabled:r}=i.initializationData||{};return qs(r?n:{},null==t?void 0:t.styles)}}const Hs=Rt(e=>new Gs(e,Rs(),js()),[{id:"paypalcommerceacceleratedcheckout"},{id:"paypalcommercecreditcards"}]);function $s(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 Ws(e){return"stripeLinkAuthenticationState"in e}class Ys{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){var t,i,n,r,o;return i=this,n=void 0,o=function*(){let i;if(!e.stripeupe)throw new gn('Unable to proceed because "options" argument is not provided.');const{container:n,gatewayId:r,methodId:o,onEmailChange:a,getStyles:s,isLoading:d}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new gn(`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(!$s(l)||!u)throw new Qi(Zi.MissingPaymentToken);const{email:h}=c.getCustomerOrThrow(),p=c.getPaymentProviderCustomerOrThrow(),m=(Ws(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}}}:{},i=yield this.scriptLoader.getStripeClient(l.initializationData,c.getCartLocale(),ba.V3,Da,Ma),this._stripeElements=yield this.scriptLoader.getElements(i,{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()||{},v=g?{defaultValues:{mode:Sa.SHIPPING,email:g}}:{},f=this._stripeElements.getElement(Pa.AUTHENTICATION)||this._stripeElements.create(Pa.AUTHENTICATION,v);f.on(Ea.CHANGE,e=>{if(!("authenticated"in e))throw new Qi(Zi.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)}),f.mount(`#${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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())})}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Pa.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 Ks=Rt(e=>new Ys(e,new ka(a())),[{id:"stripeupe"}]);var Js=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Zs{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,i,n){this.checkoutEventsUnsubscribe=this.paymentIntegrationService.subscribe(()=>Js(this,void 0,void 0,function*(){var r;const o=null==n?void 0:n.getElement(Pa.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=i.onError)||void 0===r||r.call(i,e)))}this.isMounted||(yield null==n?void 0:n.fetchUpdates(),this.mountElement(o,i.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 Vn;var t;throw new Kr}throwDisplayableStripeError(e){if(P(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}isCancellationError(e){var t;const i=null===(t=null==e?void 0:e.payment_intent.last_payment_error)||void 0===t?void 0:t.message;return!!i&&-1!==i.indexOf("canceled")}throwPaymentConfirmationProceedMessage(){throw new Kr("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 Js(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getPaymentMethodOrThrow(e),{features:r}=i.getStoreConfigOrThrow().checkoutSettings;if(!n.clientToken||!t||!r["PI-626.Block_unnecessary_payment_confirmation_for_StripeUPE"])return!1;const{paymentIntent:o}=yield t.retrievePaymentIntent(n.clientToken);return(null==o?void 0:o.status)===Oa.SUCCEEDED})}mapStripePaymentData(e,t,i=!1){const n=this.paymentIntegrationService.getState().getBillingAddress(),{firstName:r="",lastName:o="",email:a=""}=n||{},s=this._mapStripeAddress(n);if(!e)throw new nn(Xi.PaymentNotInitialized);if(!(a&&s&&s.city&&s.country&&r&&o))throw new Qi(Zi.MissingBillingAddress);return{elements:e,redirect:Ca.IF_REQUIRED,confirmParams:Object.assign({payment_method_data:Object.assign(Object.assign({},i?{allow_redisplay:"always"}:{}),{billing_details:{email:a,address:s,name:`${r} ${o}`}})},t&&{return_url:t})}}isAdditionalActionError(e){return Z(e,{code:"additional_action_required"})}isRedirectAction(e){const{type:t,data:{redirect_url:i}}=e;return"redirect_to_url"===t&&!!i}isOnPageAdditionalAction(e){const{type:t,data:{token:i}}=e;return"additional_action_requires_payment_method"===t&&!!i}updateStripePaymentIntent(e,t){return Js(this,void 0,void 0,function*(){const i=yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}}),{clientToken:n}=i.getPaymentMethodOrThrow(t);n&&this.scriptLoader.updateStripeElements({clientSecret:n})})}getStripeJsVersion(e){return e.useNewStripeJsVersion?ba.CLOVER:ba.V3}_mapStripeAddress(e){if(e){const{city:t,address1:i,address2:n,countryCode:r,postalCode:o,stateOrProvinceCode:a}=e;return Object.assign({city:t,country:r,postal_code:o,line1:i,line2:n},a?{state:a}:{})}throw new Qi(Zi.MissingBillingAddress)}}const Xs={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},Qs={position:"fixed","background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},ed="embedded-checkout-loading-indicator-rotation";class td{constructor(e){this.styles=Object.assign(Object.assign({},Xs),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=`${ed} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])})}defineAnimation(){var e;if(document.getElementById(ed))return;const t=document.createElement("style");t.id=ed,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${ed} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}class id{constructor(e){this._decimalPlaces=e}toInteger(e){return Math.round(e*Math.pow(10,this._decimalPlaces))}}const nd=["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 rd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class od{constructor(e,t,i,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=i,this.loadingIndicator=n}initialize(e){return rd(this,void 0,void 0,function*(){const{stripeocs:t}=e||{};if(!t)throw new gn('Unable to proceed because "options" argument is not provided.');const{methodId:i,gatewayId:n,container:r}=t;if(!r||!i||!n)throw new nn(Xi.PaymentNotInitialized);const o=yield this.paymentIntegrationService.loadPaymentMethod(n,{params:{method:i}}),a=o.getPaymentMethodOrThrow(i,n),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!$s(a))throw new Qi(Zi.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);return this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this._mountExpressCheckoutElement(i,r,this._stripeClient,d),Promise.resolve()})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,i,n=40){return rd(this,void 0,void 0,function*(){const r=this._shouldRequireShippingAddress(),o=Object.assign(Object.assign(Object.assign({shippingAddressRequired:r},r?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),r?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ca.AUTO,applePay:Ca.NEVER,googlePay:Ca.NEVER,amazonPay:Ca.NEVER,paypal:Ca.NEVER,klarna:Ca.NEVER},buttonHeight:n}),{cartAmount:a}=this.paymentIntegrationService.getState().getCartOrThrow(),s=Object.assign({mode:"payment",amount:this._toCents(a),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});this._stripeElements=i.elements(s),this._linkV2Element=this._stripeElements.create(Pa.EXPRESS_CHECKOUT,o),this._linkV2Element.mount(`#${t}`),this._initializeEvents(this._linkV2Element,e)})}_initializeEvents(e,t){this._shouldRequireShippingAddress()&&(e.on(Ea.SHIPPING_ADDRESS_CHANGE,e=>rd(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),e.on(Ea.SHIPPING_RATE_CHANGE,e=>rd(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),e.on(Ea.CONFIRM,e=>rd(this,void 0,void 0,function*(){return this._onConfirm(e,t)})),e.on(Ea.CANCEL,this._onCancel)}_onShippingAddressChange(e){return rd(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,i={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(i);const n=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==n?void 0:n.length)?e.resolve({shippingRates:n}):e.reject()})}_onCancel(){throw new Vn}_onShippingRateChange(e){return rd(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 rd(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 i=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(i)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,i,n,r,o,a,s,d;return rd(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(i=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===i?void 0:i.split(" ")[0])||(null===(r=null===(n=e.billingDetails)||void 0===n?void 0:n.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,i,n){var r,o,a,s,d,c,l;return{firstName:i,lastName:n,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,i,n){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:i,lastName:n,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 rd(this,void 0,void 0,function*(){if(!ca(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new nn(Xi.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:n}=i,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(i,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||n);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 i,n,r;return rd(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===(i=this._stripeClient)||void 0===i?void 0:i.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ca.IF_REQUIRED,confirmParams:{return_url:null===(n=s.confirmParams)||void 0===n?void 0:n.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Kr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return rd(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var i;const n=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:n},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:_a.Link})}}}_shouldRequireShippingAddress(){const{getCartOrThrow:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e();return!!t.physicalItems.length}_updateDisplayedPrice(){return rd(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 rd(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:e,getCartOrThrow:t}=this.paymentIntegrationService.getState(),{decimalPlaces:i}=t().currency,n=J(e().outstandingBalance,i).toFixed(i);return this._toCents(+n)})}_getAvailableCountries(){var e;return rd(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=>nd.includes(e))})}_getAvailableShippingOptions(){var e,t;return rd(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const n=i[0],r=(n.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),o=null===(e=n.selectedShippingOption)||void 0===e?void 0:e.id;return o?r.sort(e=>e.id===o?-1:0):yield this._handleShippingOptionChange(null===(t=r[0])||void 0===t?void 0:t.id),r})}_getStripeShippingOption({id:e,cost:t,description:i}){return{id:e,displayName:i,amount:this._toCents(t)}}_handleShippingOptionChange(e){return rd(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 id(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),i=this._getAmountTransformer();return i?i.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}}const ad=Rt(e=>{const t=new ka(a()),i=new td({containerStyles:Qs});return new od(e,t,new Zs(e,t),i)},[{id:"stripeocs"}]);var sd,dd,cd,ld,ud,hd,pd;class md{constructor(e,t,i=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=i}load(e){var t,i,n,r,o,a;return n=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!==(i=e.environment)&&void 0!==i?i:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-wG2z9zSQo61EIvyXmiFCo+zB3y0ZB4hsrXVcANmpP8HLthjoQJQPBh7tZKJSV8jA",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new pn;return new this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())})}}function yd(e){return"object"==typeof e&&"string"==typeof e.data.paymentMethod.encryptedSecurityCode||"string"==typeof e.data.paymentMethod.encryptedExpiryMonth}function gd(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"}(sd||(sd={})),function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2Challenge="threeDS2Challenge",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher"}(dd||(dd={})),function(e){e.SecuredFields="securedfields"}(cd||(cd={})),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"}(ld||(ld={})),function(e){e.POST="POST"}(ud||(ud={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(hd||(hd={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(pd||(pd={}));class vd extends Ji{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var fd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Sd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return fd(this,void 0,void 0,function*(){const{adyenv2:t}=e;if(!t)throw new gn('Unable to initialize payment because "options.adyenv2" argument is not provided.');this._paymentInitializeOptions=t;const i=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{originKey:n,clientKey:r,environment:o,paymentMethodsResponse:a}=i.initializationData||{},s={key:"",value:""};return n?(s.key="originKey",s.value=n):(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(i),i.method!==ld.CreditCard&&i.method!==ld.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){return fd(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=i&&i.paymentData,o=r&&r.shouldSaveInstrument,a=r&&r.shouldSetAsDefaultInstrument;if(!i)return Promise.reject(new oo(["payment"]));this._validateCardData(),yield this._paymentIntegrationService.submitOrder(n,t);const s=this._componentState;if(!s)throw new nn(Xi.PaymentNotInitialized);if(r&&gd(r)){let e={};if(yd(s)){const{encryptedCardNumber:t,encryptedSecurityCode:i,encryptedExpiryMonth:n,encryptedExpiryYear:r}=s.data.paymentMethod;e={credit_card_number_confirmation:t,expiry_month:n,expiry_year:r,verification_value:i}}if(yd(s)||-1!==["ideal","sepadirectdebit","directEbanking","giropay"].indexOf(s.data.paymentMethod.type))try{return void(yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:{formattedPayload:{bigpay_token:Object.assign(Object.assign({},e),{token:r.instrumentId}),origin:window.location.origin,browser_info:Xa(),set_as_default_stored_instrument:a||null}}})))}catch(e){return void(yield this._processAdditionalAction(e,o,a))}}try{yield this._paymentIntegrationService.submitPayment({methodId:i.methodId,paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify(Object.assign(Object.assign({},s.data.paymentMethod),{origin:window.location.origin}))},browser_info:Xa(),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 vd)}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 nn(Xi.PaymentNotInitialized);return this._adyenClient}_getPaymentInitializeOptions(){if(!this._paymentInitializeOptions)throw new gn('"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,i)=>{const{threeDS2ContainerId:n,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 i={methodId:c.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};d&&d(),t(i)},size:this._getThreeDS2ChallengeWidgetSize(),onError:e=>i(e)});o&&o(c.type===dd.ThreeDS2Challenge||c.type===dd.QRCode),l.mount(`#${a||n}`),s&&s(()=>{i(new Vn),l.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:i,lastName:n,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${i} ${n}`:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let i;return new Promise((n,r)=>{var o,a,s;if(e.cardVerificationContainerId){i=t.create(cd.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{i.mount(`#${e.cardVerificationContainerId}`)}catch(e){r(new nn(Xi.PaymentNotInitialized))}}n(i)})}_mountPaymentComponent(e){let t;const i=this._getPaymentInitializeOptions(),n=this._getAdyenClient();return new Promise((r,o)=>{switch(e.method){case ld.CreditCard:case ld.ACH:case ld.Bancontact:{const r=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:a}=e.initializationData;t=n.create(e.method,Object.assign(Object.assign({},i.options),{onChange:e=>this._updateComponentState(e),data:this._mapAdyenPlaceholderData(r,a)}));try{t.mount(`#${i.containerId}`)}catch(e){o(new nn(Xi.PaymentNotInitialized))}break}case ld.IDEAL:case ld.SEPA:if(i.hasVaultedInstruments)this._updateComponentState({data:{paymentMethod:{type:e.method}}});else{t=n.create(e.method,Object.assign(Object.assign({},i.options),{onChange:e=>this._updateComponentState(e)}));try{t.mount(`#${i.containerId}`)}catch(e){o(new nn(Xi.PaymentNotInitialized))}}break;case ld.AliPay:case ld.GiroPay:case ld.Sofort:case ld.Klarna:case ld.KlarnaPayNow:case ld.KlarnaAccount:case ld.Vipps:case ld.WeChatPayQR:this._updateComponentState({data:{paymentMethod:{type:e.method}}})}r(t)})}_processAdditionalAction(e,t,i){return fd(this,void 0,void 0,function*(){if(!ca(e)||!Z(e.body.errors,{code:"additional_action_required"}))throw e;const n=yield this._handleAction(e.body.provider_data);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:Object.assign(Object.assign({},n.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:i})}))}catch(e){return this._processAdditionalAction(e,t,i)}})}_updateComponentState(e){this._componentState=e}_validateCardData(){var e,t;const i=this._getPaymentInitializeOptions().hasVaultedInstruments?this._cardVerificationComponent:this._paymentComponent;if((null===(e=null==i?void 0:i.componentRef)||void 0===e?void 0:e.showValidation)&&i.state&&(i.componentRef.showValidation(),0===Object.keys(i.state).length||!i.state.isValid&&!i.state.issuer||"sepadirectdebit"===(null===(t=i.props)||void 0===t?void 0:t.type)&&i.state.data&&Object.values(i.state.data).some(e=>0===e.toString().trim().length)))throw new ao(this._mapCardErrors(i.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(i=>{t[i]=[{message:e[i],type:i}]}),t}}const wd=Rt(e=>new Sd(e,new md(a(),s())),[{gateway:"adyenv2"}]);class Id{constructor(e,t,i=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=i}load(e){var t,i,n,r,o,a;return n=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!==(i=e.environment)&&void 0!==i?i:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new pn;return yield this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())})}}function _d(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}var Cd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class bd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return Cd(this,void 0,void 0,function*(){const{adyenv3:t}=e;if(!t)throw new gn('Unable to initialize payment because "options.adyenv3" argument is not provided.');this._paymentInitializeOptions=t;const i=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{environment:n,clientKey:r,paymentMethodsResponse:o,installmentOptions:a}=i.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:n,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(i),i.method!==ld.CreditCard&&i.method!==ld.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){var i;return Cd(this,void 0,void 0,function*(){const{payment:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!n)throw new oo(["payment"]);const o=n.paymentData,{shouldSaveInstrument:a,shouldSetAsDefaultInstrument:s}=_d(o)?o:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};this._validateCardData(),"klarna"!==n.methodId&&"klarna_account"!==n.methodId&&"klarna_paynow"!==n.methodId||null===(i=this._paymentComponent)||void 0===i||i.submit(),yield this._paymentIntegrationService.submitOrder(r,t);const d=this._componentState||{data:{paymentMethod:{type:n.methodId}}};if(o&&gd(o)){let e={};if(yd(d)){const{encryptedCardNumber:t,encryptedSecurityCode:i,encryptedExpiryMonth:n,encryptedExpiryYear:r}=d.data.paymentMethod;e={credit_card_number_confirmation:t,expiry_month:n,expiry_year:r,verification_value:i}}try{return void(yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:{formattedPayload:{bigpay_token:Object.assign(Object.assign({},e),{token:o.instrumentId}),origin:window.location.origin,browser_info:Xa(),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:n.methodId,origin:window.location.origin}));"boletobancario"===n.methodId&&function(e){var t,i;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===(i=e.data.shopperName)||void 0===i?void 0:i.lastName)}(d)&&(c=JSON.stringify(Object.assign(Object.assign({socialSecurityNumber:d.data.socialSecurityNumber},d.data.shopperName),{type:n.methodId,origin:window.location.origin})));try{yield this._paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:{formattedPayload:Object.assign(Object.assign({credit_card_token:{token:c}},yd(d)&&d.data.installments?{installments:{value:d.data.installments.value,plan:d.data.installments.plan||"regular"}}:{}),{browser_info:Xa(),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 vd)}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 nn(Xi.PaymentNotInitialized);return this._adyenClient}_getPaymentInitializeOptions(){if(!this._paymentInitializeOptions)throw new gn('"options.adyenv3" argument was not provided during initialization.');return this._paymentInitializeOptions}_handleAction(e){return new Promise((t,i)=>{const{additionalActionOptions:n}=this._getPaymentInitializeOptions(),{onBeforeLoad:r,containerId:o,onLoad:a,onComplete:s,widgetSize:d,onActionHandled:c}=n,l=JSON.parse(e.action),u=this._getAdyenClient().createFromAction(l,{onActionHandled:e=>{c&&"function"==typeof c&&"3DS2Fingerprint"!==e.componentType&&c()},onAdditionalDetails:e=>{const i={methodId:l.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};s&&"function"==typeof s&&s(),t(i)},challengeWindowSize:d||"05",onError:e=>i(e)});r&&"function"==typeof r&&r(l.type===sd.ThreeDS2||l.type===sd.QRCode||l.type===sd.Sdk),this._mountElement(u,o),a&&"function"==typeof a&&a(()=>{i(new Vn),u.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:i,lastName:n,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${i} ${n}`:"",firstName:t?i:"",lastName:t?n:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let i;return new Promise((n,r)=>{var o,a,s;if(e.cardVerificationContainerId){i=t.create(cd.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(i,e.cardVerificationContainerId)}catch(e){r(new nn(Xi.PaymentNotInitialized))}}n(i)})}_mountPaymentComponent(e){let t;const i=this._getPaymentInitializeOptions(),n=this._getAdyenClient();return new Promise((r,o)=>{const a=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:s}=e.initializationData;t=n.create(e.method,Object.assign(Object.assign(Object.assign({},i.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,i.containerId)}catch(e){o(new nn(Xi.PaymentNotInitialized))}r(t)})}_processAdditionalAction(e,t,i,n,r){return Cd(this,void 0,void 0,function*(){if(!ca(e)||!Z(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:i}),a=i&&!t?{instrumentId:n,formattedPayload:{bigpay_token:Object.assign(Object.assign({},r),{token:n})}}:{};yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},o),{paymentData:Object.assign(Object.assign({},e),a)}))}catch(e){return this._processAdditionalAction(e,t,i,n,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 ao(this._mapCardErrors(t.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(i=>{t[i]=[{message:e[i],type:i}]}),t}_mountElement(e,t){document.getElementById(t)&&e.mount(`#${t}`)}}const Pd=Rt(e=>new bd(e,new Id(a(),s())),[{gateway:"adyenv3"}]);var Od,Ed=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ad{constructor(e,t){this.paymentIntegrationService=e,this.affirmScriptLoader=t}initialize(e){return Ed(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e.methodId);const t=this.paymentIntegrationService.getState(),{clientToken:i,config:{testMode:n}}=t.getPaymentMethodOrThrow(e.methodId);if(!i)throw new Qi(Zi.MissingPaymentMethod);this.affirm=yield this.affirmScriptLoader.load(i,n)})}execute(e,t){var i;return Ed(this,void 0,void 0,function*(){const n=null===(i=e.payment)||void 0===i?void 0:i.methodId,{useStoreCredit:r}=e;if(!this.affirm)throw new nn(Xi.PaymentNotInitialized);if(!n)throw new oo(["payment.methodId"]);yield this.paymentIntegrationService.submitOrder({useStoreCredit:r},t);const o={methodId:n,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 vd)}initializeAffirmCheckout(){var e;return null===(e=this.affirm)||void 0===e||e.checkout(this.getCheckoutInformation()),new Promise((e,t)=>{var i,n;null===(i=this.affirm)||void 0===i||i.checkout.open({onFail:e=>{"canceled"===e.reason?t(new Vn):t(new Jr)},onSuccess:t=>{e(t)}}),null===(n=this.affirm)||void 0===n||n.ui.error.on("close",()=>{t(new Vn)})})}getCheckoutInformation(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfig(),i=e.getConsignments(),n=e.getOrder(),r=e.getCart();if(!t)throw new Qi(Zi.MissingCheckoutConfig);if(!n)throw new Qi(Zi.MissingCheckout);const o=new id(n.currency.decimalPlaces),a=this.getBillingAddress(),s=this.getShippingAddress(),d=Ro(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,n),metadata:{shipping_type:this.getShippingType(i),mode:"modal",platform_type:"BigCommerce",platform_version:"",platform_affirm:""},discounts:this.getDiscounts(o,n),order_id:n.orderId?n.orderId.toString():"",shipping_amount:o.toInteger(n.shippingCostTotal),tax_amount:o.toInteger(n.taxTotal),total:o.toInteger(n.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 Qi(Zi.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 i=[];return t.lineItems.physicalItems.forEach(t=>{i.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=>{i.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=>{i.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=>{i.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.listPrice),qty:t.quantity,item_image_url:"",item_url:""})}),i}getDiscounts(e,t){const i={};return t.coupons.forEach(t=>{t.discountedAmount>0&&(i[t.code]={discount_amount:e.toInteger(t.discountedAmount),discount_display_name:t.displayName})}),t.discountAmount>0&&(i.DISCOUNTED_AMOUNT={discount_amount:e.toInteger(t.discountAmount),discount_display_name:"discount"}),i}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"}(Od||(Od={}));class Td{constructor(e=window){this.affirmWindow=e}load(e="",t){const i=t?Od.SANDBOX:Od.PROD;if(function(e,t,i,n,r,o,a){const s=e[i]||{},d=document.createElement(o),c=document.getElementsByTagName(o)[0],l=function(e,t,i){return function(){e[t]._.push([i,arguments])}};s[n]=l(s,n,"set");const u=s[n];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,n,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[i]=s}(window,{public_api_key:e,script:i},"affirm","checkout","ui","script","ready"),!this.affirmWindow.affirm)throw new pn;return Promise.resolve(this.affirmWindow.affirm)}}const kd=Rt(e=>new Ad(e,new Td),[{id:"affirm"}]);class Dd extends Ji{constructor(e){super(e||"The current order could not be finalized successfully"),this.name="OrderFinalizationNotCompletedError",this.type="order_finalization_not_completed"}}var Md=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class zd{constructor(e,t){this._paymentIntegrationService=e,this._afterpayScriptLoader=t}initialize(e){var t;return Md(this,void 0,void 0,function*(){const i=this._paymentIntegrationService.getState(),n=i.getPaymentMethod(e.methodId,e.gatewayId),r=(null===(t=i.getCart())||void 0===t?void 0:t.currency.code)||"",o=this._mapCurrencyToISO2(r),a=Wt(i.getStoreConfigOrThrow().checkoutSettings.features,"PI-4789.afterpay_script_use_https",!1);if(!n)throw new Qi(Zi.MissingPaymentMethod);this._afterpaySdk=yield this._afterpayScriptLoader.load(n,o,a)})}deinitialize(){return this._afterpaySdk&&(this._afterpaySdk=void 0),Promise.resolve()}execute(e,t){var i;return Md(this,void 0,void 0,function*(){if(!e.payment)throw new oo(["payment.gatewayId","payment.methodId"]);const{gatewayId:n,methodId:r}=e.payment;if(!n||!r)throw new oo(["payment.gatewayId","payment.methodId"]);const{useStoreCredit:o}=e;void 0!==o&&(yield this._paymentIntegrationService.applyStoreCredit(o)),yield this._loadPaymentMethod(n,r,t);const a=this._paymentIntegrationService.getState();yield this._paymentIntegrationService.validateCheckout(a.getCheckout(),t);const s=(null===(i=a.getCart())||void 0===i?void 0:i.currency.code)||"",d=this._mapCurrencyToISO2(s);return this._redirectToAfterpay(d,a.getPaymentMethod(r,n)),new Promise(()=>{})})}finalize(e){var t,i,n;return Md(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new Qi(Zi.MissingCheckout);if(!(null==a?void 0:a.payment.token))throw new Qi(Zi.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(),ca(e))throw new Dd(null===(n=null===(i=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===i?void 0:i[0])||void 0===n?void 0:n.message)}})}_redirectToAfterpay(e,t){if(!this._afterpaySdk||!(null==t?void 0:t.clientToken))throw new nn(Xi.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,i){var n;return Md(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},i),{params:Object.assign(Object.assign({},null==i?void 0:i.params),{method:t})}))}catch(e){if(e instanceof Qn&&422===(null===(n=e.body)||void 0===n?void 0:n.status))throw new gn("Afterpay can't process your payment for this order, please try another payment method");throw e}})}}var Nd,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"}(Nd||(Nd={})),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 Fd{constructor(e){this._scriptLoader=e}load(e,t,i=!1){return n=this,r=void 0,a=function*(){const n=e.config.testMode||!1,r=this._getScriptURI(t,n,i);return this._scriptLoader.loadScript(r).then(()=>{if(!function(e){return"AfterPay"in e}(window))throw new pn;return window.AfterPay})},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())});var n,r,o,a}_getScriptURI(e,t,i=!1){return"US"===e?i?t?xd.HTTPS_SANDBOX:xd.HTTPS_PROD:t?xd.SANDBOX:xd.PROD:i?t?Nd.HTTPS_SANDBOX:Nd.HTTPS_PROD:t?Nd.SANDBOX:Nd.PROD}}const Rd=Rt(e=>new zd(e,new Fd(o())),[{gateway:"afterpay"},{id:"afterpay"}]);var Ld=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Bd{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return Ld(this,void 0,void 0,function*(){const{methodId:t,amazonpay:i}=e;if(!t)throw new gn('Unable to proceed because "methodId" argument is not provided.');const n=this.paymentIntegrationService.getState(),{features:r}=n.getStoreConfigOrThrow().checkoutSettings,o=n.getPaymentMethodOrThrow(t),a=o.initializationData||{},{paymentToken:s="",region:d="",isButtonMicroTextDisabled:c}=a;if(yield this.amazonPayV2PaymentProcessor.initialize(o),this._isReadyToPay(s))(null==i?void 0:i.editButtonId)&&this._bindEditButton(i.editButtonId,s,"changePayment",this._isModalFlow(d));else{const{id:e}=this._createContainer();if(this._amazonPayButton=this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:n,containerId:e,decoupleCheckoutInitiation:this._isOneTimeTransaction(r,d.toUpperCase()),methodId:t,placement:an.Checkout,isButtonMicroTextDisabled:c}),!this._amazonPayButton)throw new gn("Unable to render the Amazon Pay button to an invalid HTML container element.")}})}execute(e,t){return Ld(this,void 0,void 0,function*(){const{payment:i}=e;if(!i)throw new oo(["payment"]);const{methodId:n}=i,r=this.paymentIntegrationService.getState(),{features:o}=r.getStoreConfigOrThrow().checkoutSettings,a=r.getPaymentMethodOrThrow(n).initializationData||{},{paymentToken:s="",region:d=""}=a;if(this._isReadyToPay(s)||this._isOneTimeTransaction(o,d.toUpperCase())){const i={methodId:n,paymentData:{nonce:s||"apb"}};yield this.paymentIntegrationService.submitOrder(e,t);try{return void(yield this.paymentIntegrationService.submitPayment(i))}catch(e){if(!(ca(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:i}=t.data;if(s)return new Promise(()=>window.location.assign(i));this.amazonPayV2PaymentProcessor.prepareCheckout(JSON.parse(i))}}var c;return this._getAmazonPayButton().click(),this._isModalFlow(d)?new Promise((e,t)=>{const i=()=>{window.removeEventListener("focus",i),t(new Vn("Shopper needs to login to Amazonpay to continue"))};window.addEventListener("focus",i)}):new Promise(V)})}finalize(){return Promise.reject(new vd)}deinitialize(){return Ld(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize(),this._amazonPayButton=void 0})}_bindEditButton(e,t,i,n){const r=document.getElementById(e);if(r&&r.parentNode){if(!n){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>{this._showLoadingSpinner()})}this.amazonPayV2PaymentProcessor.bindButton(e,t,i)}}_isModalFlow(e){return"us"===e}_showLoadingSpinner(){return Ld(this,void 0,void 0,function*(){yield this.paymentIntegrationService.widgetInteraction(()=>new Promise(V))})}_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 tn(this._amazonPayButton,()=>new nn(Xi.PaymentNotInitialized))}_isOneTimeTransaction(e,t){return this.amazonPayV2PaymentProcessor.isPh4Enabled(e,t)&&e["INT-6399.amazon_pay_apb"]}_isReadyToPay(e){return!!e}}const jd=Rt(e=>new Bd(e,yn()),[{id:"amazonpay"}]);var Ud,qd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e.Shipping="Shipping",e.Subtotal="Subtotal",e.StoreCredit="Store Credit"}(Ud||(Ud={}));class Vd{constructor(e,t,i,n,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=i,this._braintreeSdk=n,this._applePayScriptLoader=r,this._shippingLabel=Ud.Shipping,this._subTotalLabel=Ud.Subtotal,this._storeCreditLabel=Ud.StoreCredit}initialize(e){var t,i,n,r;return qd(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new gn('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)||Ud.Shipping,this._subTotalLabel=(null===(i=e.applepay)||void 0===i?void 0:i.subtotalLabel)||Ud.Subtotal,this._storeCreditLabel=(null===(n=e.applepay)||void 0===n?void 0:n.storeCreditLabel)||Ud.StoreCredit;const a=(yield this._paymentIntegrationService.loadPaymentMethod(o)).getPaymentMethodOrThrow(o);(null===(r=a.initializationData)||void 0===r?void 0:r.gateway)===jn.BRAINTREE&&a.clientToken&&this._braintreeSdk.initialize(a.clientToken)})}execute(e,t){return qd(this,void 0,void 0,function*(){const{payment:i}=e,n=this._paymentIntegrationService.getState();if(!i)throw new oo(["payment"]);const{methodId:r}=i,o=n.getPaymentMethodOrThrow(r),a=this._getBaseRequest(n,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 vd)}deinitialize(){return Promise.resolve()}_getBaseRequest(e,t){const i=e.getCheckoutOrThrow(),n=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),{storeProfile:{storeCountryCode:o,storeName:a}}=r,{currency:{code:s,decimalPlaces:d}}=n,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=t,{grandTotal:u,isStoreCreditApplied:h,outstandingBalance:p}=i,m=[{label:this._subTotalLabel,amount:`${i.subtotal.toFixed(d)}`}];if(i.taxes.forEach(e=>m.push({label:e.name,amount:`${e.amount.toFixed(d)}`})),m.push({label:this._shippingLabel,amount:`${i.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,i){e.onvalidatemerchant=i=>qd(this,void 0,void 0,function*(){try{const{body:n}=yield this._onValidateMerchant(t,i);e.completeMerchantValidation(n)}catch(e){throw new Error("Merchant validation failed")}}),e.oncancel=()=>qd(this,void 0,void 0,function*(){return i.reject(new Vn("Continue with applepay"))}),e.onpaymentauthorized=n=>this._onPaymentAuthorized(n,e,t,i)}_onValidateMerchant(e,t){return qd(this,void 0,void 0,function*(){const i=[`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:i})})}_onPaymentAuthorized(e,t,i,n){var r;return qd(this,void 0,void 0,function*(){const{token:o}=e.payment;let a;(null===(r=i.initializationData)||void 0===r?void 0:r.gateway)===jn.BRAINTREE&&(a=yield this._getBraintreeDeviceData());const s={methodId:i.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),n.resolve()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),n.reject(new nn(Xi.PaymentNotInitialized))}})}_getBraintreeDeviceData(){return qd(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const Gd=Rt(e=>{const{getHost:t}=e.getState(),n=new bn(e);return new Vd(i({host:t()}),e,new Yn,new Ln(new qn(a(),window,n)),new Kn(new r))},[{id:"applepay"}]),Hd={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},$d=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 Wd(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 Yd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Kd{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.paypalSdkHelper=i,this.loadingIndicator=n}initialize(e){return Yd(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments:i}=e||{};if(this.bigcommerce_payments=i,!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(t),{container:o,bannerContainerId:a}=i,{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,n.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),i.onInit&&"function"==typeof i.onInit&&i.onInit(()=>this.renderButton(t,i)),(void 0===i.shouldRenderPayPalButtonOnInitialization||i.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(t,i))})}execute(e,t){return Yd(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{onError:r}=this.bigcommerce_payments||{};if(!i)throw new oo(["payment"]);const{methodId:o,paymentData:a}=i;if(this.isPayPalVaultedInstrumentPaymentData(a)&&!this.orderId&&(this.orderId=yield this.createOrder()),!this.orderId)throw new Jr;const s=this.isPayPalVaultedInstrumentPaymentData(a)?this.prepareVaultedInstrumentPaymentPayload(o,this.orderId,a):this.preparePaymentPayload(o,this.orderId,a);try{yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment(s)}catch(e){return this.isProviderError(e)&&(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i.methodId),yield new Promise((e,t)=>{var n;this.bigcommerce_payments&&(null===(n=this.paypalButton)||void 0===n||n.close(),this.renderButton(i.methodId,this.bigcommerce_payments),this.handleError(new Error("INSTRUMENT_DECLINED"),r)),t()})),this.handleError(e,r),Promise.reject()}})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,i){const{instrumentId:n,shouldSetAsDefaultInstrument:r}=i,o=!this.isTrustedVaultingFlow(i);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:n,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:n}}}}}preparePaymentPayload(e,t,i){const{shouldSaveInstrument:n=!1,shouldSetAsDefaultInstrument:r=!1}=_d(i)?i:{};return{methodId:e,paymentData:{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=n.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t;if(!a)throw new gn('Unable to initialize payment because "container" argument is not provided.');const u={fundingSource:i.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onError:e=>this.handleError(e,s),onCancel:()=>this.toggleLoadingIndicator(!1)};this.paypalButton=i.Buttons(u),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}handleClick(e,t){return Yd(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;yield null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return Yd(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&&gd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),i=null==t?void 0:t.find(t=>Wd(t)&&t.bigpayToken===e.instrumentId);return!(Wd(i)&&!i.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&gd(e)&&_d(e)}renderMessages(e,t,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:$d(i)};e.Messages(n).render(`#${t}`)}isProviderError(e){var t,i,n;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(n=null===(i=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===i?void 0:i.provider_error)||void 0===n?void 0:n.code)}}const Jd=Rt(e=>new Kd(e,vr(e),zr(),new td({containerStyles:Hd})),[{id:"bigcommerce_payments"}]);function Zd(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var Xd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Qd{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsRequestSender=t,this.bigCommercePaymentsSdk=i,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){var t,i;return Xd(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_fastlane:r}=e;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(this.methodId=n,!r)throw new gn('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 gn('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 gn('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(n),{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=Br(c?null===(i=null==s?void 0:s.initializationData)||void 0===i?void 0:i.fastlaneStyles:{},null==r?void 0:r.styles);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(n)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(n))})}execute(e,t){return Xd(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{paymentData:r,methodId:o}=i,a=r&&gd(r);try{yield this.paymentIntegrationService.submitOrder(n,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 vd)}deinitialize(){return Xd(this,void 0,void 0,function*(){return Promise.resolve()})}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getCustomerOrThrow(),n=e.getPaymentProviderCustomer(),r=Zd(n)?n:{},o=this.bigCommercePaymentsFastlaneUtils.getStorageSessionId();return!(!i.isGuest||(null==r?void 0:r.authenticationState)===kr.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}runPayPalAuthenticationFlowOrThrow(e){return Xd(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getCustomer(),r=t.getBillingAddress(),o=(null==n?void 0:n.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===kr.CANCELED?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(i.id)}catch(e){}})}initializePayPalPaymentComponent(){return Xd(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),t=e.phone,i=`${e.firstName} ${e.lastName}`.trim(),n=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),r={fields:Object.assign({cardholderName:{prefill:i,enabled:!0}},t&&{phoneNumber:{prefill:t}})};this.paypalComponentMethods=yield n.FastlaneCardComponent(r)})}renderPayPalPaymentComponent(e){const t=this.getPayPalComponentMethodsOrThrow();if(!e)throw new gn('Unable to render card component because "container" argument is not provided.');t.render(e)}getPayPalComponentMethodsOrThrow(){if(!this.paypalComponentMethods)throw new pn;return this.paypalComponentMethods}prepareVaultedInstrumentPaymentPayload(e,t){return Xd(this,void 0,void 0,function*(){const{instrumentId:i}=t,n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),r=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&n.config.is3dsEnabled?yield this.get3DSNonce(i):i;return yield this.createOrder(r),{methodId:e,paymentData:{formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:r}}}}})}preparePaymentPayload(e,t){return Xd(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getBillingAddressOrThrow(),r=i.getPaymentMethodOrThrow(e),o=`${n.firstName} ${n.lastName}`.trim(),{getPaymentToken:a}=this.getPayPalComponentMethodsOrThrow(),{id:s}=yield a({name:{fullName:o},billingAddress:this.bigCommercePaymentsFastlaneUtils.mapBcToPayPalAddress(n)}),d=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&r.config.is3dsEnabled,{shouldSaveInstrument:c=!1,shouldSetAsDefaultInstrument:l=!1}=_d(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 Xd(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getCartOrThrow().id;if(this.methodId){const{orderId:i}=yield this.bigCommercePaymentsRequestSender.createOrder(this.methodId,{cartId:t,fastlaneToken:e});this.orderId=i}})}get3DSNonce(e){var t;return Xd(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getCartOrThrow(),r=i.getOrderOrThrow(),o=i.getStoreConfigOrThrow().links.checkoutLink,a=null===(t=this.paypalFastlaneSdk)||void 0===t?void 0:t.ThreeDomainSecureClient;if(!a)throw new pn;const s={amount:r.orderAmount.toFixed(2),currency:n.currency.code,nonce:e,threeDSRequested:this.threeDSVerificationMethod===Pr.Always,transactionContext:{experience_context:{locale:"en-US",return_url:o,cancel_url:o}}},d=yield a.isEligible(s);if(this.threeDSVerificationMethod===Pr.Always&&!d)throw new Jr;if(d){const{liabilityShift:e,authenticationState:t,nonce:i}=yield a.show();if(e===er.No||e===er.Unknown||t===Or.Errored||t===Or.Cancelled)throw new Jr;if(t===Or.Succeeded&&[er.Yes,er.Possible].includes(e))return i}return e})}handlePayPalStoredInstrumentChange(e){return Xd(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:i,selectedCard:n}=yield t.profile.showCardSelector();if(i){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),i=Zd(t)?t:{},r=this.bigCommercePaymentsFastlaneUtils.mapPayPalToBcInstrument(e,n)[0];return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},i),{instruments:[r]})),r}})}isBigcommercePaymentsFastlaneThreeDSAvailable(){return Wt(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 ec=Rt(e=>{const{getHost:t}=e.getState();return new Qd(e,new mr(i({host:t()})),zr(),Rr())},[{id:"bigcommerce_payments_fastlane"}]);var tc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ic{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i,this.paypalSdkHelper=n}initialize(e){return tc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_paylater:i}=e||{};if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:o=[],orderId:a}=r.initializationData||{},{bannerContainerId:s,container:d}=i;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,n.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,i))})}execute(e,t){return tc(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);if(!this.orderId)throw new Jr;yield this.paymentIntegrationService.submitOrder(n,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new vd)}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 gn('Unable to initialize payment because "container" argument is not provided.');const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=n.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u=[i.FUNDING.PAYLATER,i.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=i.Buttons(t),this.bigCommercePaymentsButtons.isEligible()||e!==i.FUNDING.PAYLATER){if(!this.bigCommercePaymentsButtons.isEligible()&&e===i.FUNDING.CREDIT)throw new vn(`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 tc(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;t&&"function"==typeof t&&(yield t(()=>(this.toggleLoadingIndicator(!0),i()),n))})}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,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:$d(i)};e.Messages(n).render(`#${t}`)}}const nc=Rt(e=>new ic(e,vr(e),new td({containerStyles:Hd}),zr()),[{id:"bigcommerce_payments_paylater"}]);class rc extends Qn{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var oc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ac{constructor(e,t,i,n=3e3,r=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i,this.pollingInterval=n,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=V}initialize(e){return oc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,bigcommerce_payments_ratepay:n}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_ratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=n;if(!o)throw new gn('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new gn('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,t),{merchantId:d}=s.initializationData||{};if(!d)throw new gn("Unable to initialize payment because merchantId argument is not provided.");this.bigcommerce_payments_ratepay=n,yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i),this.createFraudNetScript(d,i,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return oc(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{getFieldsValues:r}=this.bigcommerce_payments_ratepay||{};if(!i)throw new oo(["payment"]);if(!r||"function"!=typeof r)throw new gn('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:i.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(n,t),yield this.paymentIntegrationService.submitPayment({methodId:i.methodId,paymentData:d}),yield new Promise((e,t)=>{this.initializePollingMechanism(i.methodId,e,t,i.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new vd)}deinitialize(){const{legalTextContainer:e}=this.bigcommerce_payments_ratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],i=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),i.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),i=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${i}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const i=e,n=t.split("#")[1],r=document.getElementById(n),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",i),null==o||o.prepend(a);const s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(i))throw new gn('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${i}`)}handleError(e){const{onError:t}=this.bigcommerce_payments_ratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,i){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,i),{testMode:r}=n.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 oc(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,i,n){return oc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus("bigcommerce_payments_apms",{params:{useMetadata:!0}}),o=r===ar.PollingStop,a=r===ar.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return i();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,bigcommerce_payments_ratepay:this.bigcommerce_payments_ratepay}),this.handleError(new rc)}catch(e){this.handleError(e),i()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const sc=Rt(e=>new ac(e,vr(e),new td({containerStyles:Object.assign(Object.assign({},Hd),{position:"fixed"})})),[{gateway:"bigcommerce_payments_apms",id:"ratepay"}]);var dc;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification",e.CardExpiryVerification="cardExpiryVerification"}(dc||(dc={}));const cc=dc;function lc(e){return cc.CardNumber in e&&cc.CardName in e&&cc.CardExpiry in e}function uc(e){return cc.CardNumberVerification in e&&cc.CardCodeVerification in e&&cc.CardExpiryVerification in e}var hc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class pc{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdk=i,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){return hc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_creditcards:i}=e,n=i,{form:r,onCreditCardFieldsRenderingError:o,onLoadComplete:a}=n||{};if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new gn('Unable to proceed because "options.bigcommerce_payments_creditcards.form" argument is not provided.');this.hostedFormOptions=r,this.isCreditCardForm=lc(r.fields),this.isCreditCardVaultedForm=uc(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 hc(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{methodId:r,paymentData:o}=i||{};if(!i||!r)throw new oo(["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(n,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e,t,i,n;return hc(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===(i=this.numberField)||void 0===i?void 0:i.close(),yield null===(n=this.nameField)||void 0===n?void 0:n.close(),Promise.resolve()})}preparePaymentPayload(e,t,i,n){const{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=_d(t)?t:{},a=t&&gd(t)?t.instrumentId:void 0,s=H({verification_nonce:n,token:a},k);return{methodId:e,paymentData:{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o,instrumentId:a,formattedPayload:Object.assign(Object.assign({},n||a?{bigpay_token:s}:{}),i?{card_with_order:{order_id:i}}:{})}}}initializeFields(e,t){return hc(this,void 0,void 0,function*(){const{fields:i,styles:n}=e,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),o=this.getExecuteCallback(i),a=Object.assign({style:this.getInputStyles(n),onApprove:({orderID:e,vaultSetupToken:t,liabilityShift:i})=>{if(i===er.No||i===er.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Kr},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 nn(Xi.PaymentNotInitialized);try{this.stylizeInputContainers(i),lc(i)&&(yield this.renderFields(i)),uc(i)&&(yield this.renderVaultedFields(i))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return uc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>hc(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:()=>hc(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,i,n,r;return hc(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===(i=e.cardExpiry)||void 0===i?void 0:i.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(n=e.cardName)||void 0===n?void 0:n.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,i,n;return hc(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===(i=e.cardExpiryVerification)||void 0===i?void 0:i.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(n=e.cardNumberVerification)||void 0===n?void 0:n.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(_d(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(gd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return hc(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i={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(i)}catch(e){throw new Kr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return hc(this,void 0,void 0,function*(){const i=this.getCardFieldsOrThrow(),n=yield i.getState().then(e=>e),r=this.getValidityData(n);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 ao(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const i=Object.keys(t);return{isValid:i.every(e=>{var i;return null===(i=t[e])||void 0===i?void 0:i.isValid}),errors:i.reduce((e,i)=>{var n;const r=this.mapFieldType(i);return Object.assign(Object.assign({},e),{[r]:(null===(n=t[i])||void 0===n?void 0:n.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case cc.CardCode:case cc.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case cc.CardNumber:case cc.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case cc.CardExpiry:case cc.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(i=>{var n,r;t[i]=[{message:(null===(r=null===(n=e[i])||void 0===n?void 0:n[0])||void 0===r?void 0:r.message)||"",type:i}]}),t}mapFieldType(e){switch(e){case"name":return cc.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?cc.CardNumber:cc.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?cc.CardExpiry:cc.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?cc.CardCode:cc.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new nn(Xi.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,i,n;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.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 i;null===(i=null==e?void 0:e.onValidate)||void 0===i||i.call(e,this.getValidityData(t))}onFocusHandler(e,t){var i;null===(i=null==e?void 0:e.onFocus)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var i;null===(i=null==e?void 0:e.onBlur)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var i;null===(i=null==e?void 0:e.onEnter)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,i;const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(e),o=n.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===(i=null==r?void 0:r.initializationData)||void 0===i?void 0:i.isBigCommercePaymentsAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return hc(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getPaymentMethodOrThrow(e),{initializationData:r}=n;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(n,i.currency.code,i.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const mc=Rt(e=>new pc(e,vr(e),zr(),Rr()),[{id:"bigcommerce_payments_creditcards"}]);var yc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class gc{constructor(e,t,i,n,r=3e3,o=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdkHelper=i,this.loadingIndicator=n,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=V,this.isPollingEnabled=!1}initialize(e){return yc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,bigcommerce_payments_apms:n}=e;if(this.bigCommercePaymentsAlternativeMethods=n,!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(i,t),{orderId:a,shouldRenderFields:s}=o.initializationData||{},d=r.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=Wt(d,"PAYPAL-5624.bcp_ideal_polling"),a?this.orderId=a:(this.paypalApms=yield this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(o,r.getCartOrThrow().currency.code),this.loadingIndicatorContainer=n.container.split("#")[1],this.renderButton(i,t,n),s&&this.renderFields(i,n))})}execute(e,t){return yc(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{methodId:r,gatewayId:o}=i;if(!this.orderId)throw new Jr;this.isPollingEnabled&&"ideal"===r&&(yield new Promise((e,t)=>{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)||(yield this.paymentIntegrationService.submitOrder(n,t)),yield this.bigCommercePaymentsIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new vd)}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,i,n){return yc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus(n),o=r===ar.Approved,a=r===ar.PollingError;if(o)return this.deInitializePollingMechanism(),t();if(a)return i();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,bigCommercePaymentsAlternativeMethods:this.bigCommercePaymentsAlternativeMethods}),this.handleError(new rc)}catch(e){i()}})}deInitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deInitializePollingMechanism()}reinitializeStrategy(e){return yc(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,i){const n=this.getPaypalAmpsSdkOrThrow(),r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t),{buttonStyle:o}=r.initializationData||{},{container:a,onError:s,onRenderButton:d,submitForm:c}=i,l={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),onInit:(e,t)=>i.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,i),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deInitializePollingMechanism()},onError:e=>{this.deInitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>yc(this,void 0,void 0,function*(){return i.onValidate(t.resolve,t.reject)})};this.bigCommercePaymentsButton=n.Buttons(l),this.bigCommercePaymentsButton.isEligible()&&(d&&"function"==typeof d&&d(),this.bigCommercePaymentsButton.render(a))}onCreateOrder(e,t,i){return yc(this,void 0,void 0,function*(){const{onValidate:n}=i;yield n(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),V);const r=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms");if(this.isNonInstantPaymentMethod(e)){const i={useStoreCredit:!1},n={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(i,n),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 i=this.getPaypalAmpsSdkOrThrow(),n=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=n.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new gn('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}}};i.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in or}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new pn;return this.paypalApms}}const vc=Rt(e=>new gc(e,vr(e),zr(),new td({containerStyles:Hd})),[{gateway:"bigcommerce_payments_apms"}]);class fc{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){const{gatewayId:t,methodId:i,bigcommerce_payments_apms:n}=e;if(this.bigCommercePaymentsAlternativeMethods=n,!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');return Promise.resolve()}execute(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{methodId:r,gatewayId:o}=i;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(n,t),yield this.paymentIntegrationService.submitPayment({methodId:r,gatewayId:o,paymentData:e})}catch(e){if(function(e){var t,i;return ca(e)&&(null===(i=null===(t=e.body)||void 0===t?void 0:t.additional_action_required)||void 0===i?void 0:i.data.redirect_url)}(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise((e,i)=>{window.location.replace(t),i()})}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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}deinitialize(){return Promise.resolve()}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};t&&"function"==typeof t&&t(e)}}const Sc=Rt(e=>new fc(e,vr(e)),[{gateway:"bigcommerce_payments_apms",id:"klarna"},{gateway:"bigcommerce_payments_apms",id:"afterpay"}]);var wc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ic{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i}initialize(e){var t,i;return wc(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_venmo:r}=e||{};if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);(null===(t=o.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(i=o.initializationData)||void 0===i?void 0:i.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),this.loadingIndicatorContainer=r.container.split("#")[1],this.renderButton(n,r))})}execute(e,t){return wc(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);if(!this.orderId)throw new Jr;yield this.paymentIntegrationService.submitOrder(n,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=n.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u={fundingSource:i.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=i.Buttons(u),!this.paypalButton.isEligible())throw new vn("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 wc(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;yield t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}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 _c=Rt(e=>new Ic(e,vr(e),new td({styles:{backgroundColor:"black"}})),[{id:"bigcommerce_payments_venmo"}]);class Cc{initialize(e){this._blueSnapSdk=e}initialize3ds(e,t){return i=this,n=void 0,o=function*(){const i=this._getBlueSnapSdk();return new Promise((n,r)=>{i.threeDsPaymentsSetup(e,e=>"1"===e.code?n(e.threeDSecure.threeDSecureReferenceId):r(new Kr)),i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_getBlueSnapSdk(){return tn(this._blueSnapSdk,()=>new nn(Xi.PaymentNotInitialized))}}function bc(e){return cc.CardNumber in e}function Pc(e){return cc.CardCodeVerification in e||cc.CardNumberVerification in e}var Oc,Ec,Ac,Tc,kc,Dc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Mc{constructor(e,t,i,n){this._scriptLoader=e,this._paymentIntegrationService=t,this._blueSnapDirectHostedForm=i,this._blueSnapDirect3ds=n}initialize(e){return Dc(this,void 0,void 0,function*(){const{methodId:t,gatewayId:i,creditCard:n}=e;if(!i||!n)throw new gn;const r=yield this._paymentIntegrationService.loadPaymentMethod(i,{params:{method:t,bigpayToken:n.bigpayToken}}),{config:{testMode:o,is3dsEnabled:a},clientToken:s}=r.getPaymentMethodOrThrow(t,i);this._blueSnapSdk=yield this._scriptLoader.load(o),this._paymentFieldsToken=s,this._shouldUseHostedFields=bc(n.form.fields)||Pc(n.form.fields)&&!!n.form.fields.cardNumberVerification,this._shouldUseHostedFields&&(this._blueSnapDirectHostedForm.initialize(this._blueSnapSdk,n.form.fields),yield this._blueSnapDirectHostedForm.attach(this._getPaymentFieldsToken(),n,a))})}execute(e){return Dc(this,void 0,void 0,function*(){if(!e.payment)throw new oo(["payment"]);if(!this._blueSnapSdk)throw new oo(["payment"]);const{paymentData:t}=e.payment,{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:n}=_d(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,!(_d(t)&&gd(t))):void 0;if(yield this._paymentIntegrationService.submitOrder(),_d(t)&&gd(t)&&this._paymentFieldsToken&&t.instrumentId){if(a){this._blueSnapDirect3ds.initialize(this._blueSnapSdk);const{last4:e,brand:i}=this._paymentIntegrationService.getState().getCardInstrumentOrThrow(t.instrumentId),n=Object.assign({last4Digits:e,ccType:i.toUpperCase()},this._getBlueSnapDirectThreeDSecureData());o=yield this._blueSnapDirect3ds.initialize3ds(this._paymentFieldsToken,n)}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:!!n})}))}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:i,set_as_default_stored_instrument:n}}}))})}finalize(){return Promise.reject(new vd)}deinitialize(){return this._shouldUseHostedFields&&this._blueSnapDirectHostedForm.detach(),Promise.resolve()}_getBlueSnapDirectThreeDSecureData(){var e;const{getBillingAddress:t,getShippingAddress:i,getCustomer:n,getCheckoutOrThrow:r,getCartOrThrow:o}=this._paymentIntegrationService.getState(),a=t(),s=i(),d=(null===(e=n())||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 tn(this._paymentFieldsToken,()=>new Qi(Zi.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"}(Oc||(Oc={})),function(e){e.ON_BLUR="onBlur",e.ON_SUBMIT="onSubmit"}(Ec||(Ec={})),function(e){e.EMPTY="empty",e.INVALID="invalid",e.THREE_DS_NOT_ENABLED="3D Secure is not enabled"}(Ac||(Ac={})),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"}(Tc||(Tc={})),function(e){e.CardCode="cvv",e.CardExpiry="exp",e.CardName="noc",e.CardNumber="ccn"}(kc||(kc={}));const zc={[kc.CardNumber]:cc.CardNumber,[kc.CardExpiry]:cc.CardExpiry,[kc.CardName]:cc.CardName,[kc.CardCode]:cc.CardCode},Nc={empty:{[cc.CardNumber]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[cc.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[cc.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date is required",type:"required"},[cc.CardCode]:{fieldType:"cardCode",message:"CVV is required",type:"required"},[cc.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}},invalid:{[cc.CardNumber]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[cc.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[cc.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date must be a valid future date in MM / YY format",type:"invalid_card_expiry"},[cc.CardCode]:{fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},[cc.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&&(bc(t)?this._hostedInputValidator.initialize():Pc(t)&&t.cardNumberVerification&&this._hostedInputValidator.initializeValidationFields())}attach(e,t,i){var n,r,o,a,s=t.form,{fields:d}=s,c=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(s,["fields"]);return void 0===i&&(i=!1),n=this,r=void 0,a=function*(){const t=this._getBlueSnapSdk();if(!bc(d)&&!Pc(d))throw new gn("Field options must be of type HostedCardFieldOptionsMap");return this._onValidate=c.onValidate,bc(d)&&this._setCustomBlueSnapAttributes(d),Pc(d)&&this._setCustomStoredCardsBlueSnapAttributes(d),new Promise(n=>{const r=this._getHostedPaymentFieldsOptions(e,d,c,n,i);t.hostedPaymentFieldsCreate(r),bc(d)&&this._nameOnCardInput.attach(r,d.cardName.accessibilityLabel,d.cardName.placeholder)})},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,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,i])=>Object.assign(Object.assign({},e),{[t]:i.map(({message:e,type:t})=>({message:e,type:t}))}),{});throw new ao(e)}return this}submit(e,t=!1){return new Promise((i,n)=>this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(e=>this._isBlueSnapDirectCallbackError(e)?n(new Kr(e.statusCode===Tc.THREE_DS_AUTH_FAILED?e.error[0].errorDescription:`Submission failed with status: ${e.statusCode} and errors: ${JSON.stringify(e.error)}`)):i(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:i,onBlur:n,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(i),onBlur:this._usetUiEventCallback(n),onError:this._handleError(r),onType:(e,t)=>null==o?void 0:o({cardType:Oc[t]}),onEnter:this._usetUiEventCallback(a),onValid:e=>null==r?void 0:r(this._hostedInputValidator.validate({tagId:e}))}},bc(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:i}){return Object.entries(Object.assign(Object.assign(Object.assign({},e&&{input:e}),t&&{".invalid":t}),i&&{":focus":i})).reduce((e,[t,i])=>Object.assign(Object.assign({},e),{[t]:Object.entries(i).reduce((e,[t,i])=>Object.assign(Object.assign({},e),{[x(t)]:i}),{})}),{})}_handleError(e){return(t,i,n,r)=>{if(i===Tc.INVALID_OR_EMPTY&&t&&function(e){return void 0!==e&&[Ac.EMPTY,Ac.INVALID].includes(e)}(n))return null==e?void 0:e(this._hostedInputValidator.validate({tagId:t,errorDescription:n}));throw new Kr(`An unexpected error has occurred: ${JSON.stringify({tagId:t,errorCode:i,errorDescription:n,eventOrigin:r})}`)}}_usetUiEventCallback(e){return t=>{e&&e({fieldType:zc[t]})}}_getBlueSnapSdk(){return tn(this._blueSnapSdk,()=>new nn(Xi.PaymentNotInitialized))}_setCustomBlueSnapAttributes(e){const{cardNumber:t,cardExpiry:i,cardCode:n,cardName:r}=e,o=document.getElementById(t.containerId),a=document.getElementById(i.containerId),s=n&&document.getElementById(n.containerId),d=document.getElementById(r.containerId);if(!(o&&a&&s&&d))throw new gn("Unable to create hosted payment fields to invalid HTML container elements.");o.dataset.bluesnap=kc.CardNumber,a.dataset.bluesnap=kc.CardExpiry,s.dataset.bluesnap=kc.CardCode,d.dataset.bluesnap=kc.CardName}_setCustomStoredCardsBlueSnapAttributes(e){const{cardNumberVerification:t,cardCodeVerification:i}=e,n=t&&document.getElementById(t.containerId),r=i&&document.getElementById(i.containerId);(n||r)&&(n&&(n.dataset.bluesnap=kc.CardNumber),r&&(r.dataset.bluesnap=kc.CardCode))}}class Fc{constructor(){this._errors={}}initialize(){this._errors={cardNumber:[Nc.empty.cardNumber],cardExpiry:[Nc.empty.cardExpiry],cardCode:[Nc.empty.cardCode],cardName:[Nc.empty.cardName]}}initializeValidationFields(){this._errors={cardNumberVerification:[Nc.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 i=this._errors.cardNumberVerification?cc.CardNumberVerification:zc[e];this._errors[i]=t?[Nc[t][i]]:[]}}class Rc{attach({style:e,onFieldEventHandler:{onFocus:t,onBlur:i,onValid:n,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(i,n,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(kc.CardName)}}_handleBlur(e,t,i){return({target:n})=>{var r,o;null==e||e(kc.CardName),n instanceof HTMLInputElement&&(/\w{1,200}/.test(n.value)?(this._applyStyles(null===(r=this._style)||void 0===r?void 0:r.input),null==t||t(kc.CardName)):(this._applyStyles(null===(o=this._style)||void 0===o?void 0:o[".invalid"]),null==i||i(kc.CardName,Tc.INVALID_OR_EMPTY,Ac.EMPTY,Ec.ON_BLUR)))}}_handleEnter(e){return()=>null==e?void 0:e(kc.CardName)}_applyStyles(e={}){const t={color:e.color,fontFamily:e["font-family"],fontSize:e["font-size"],fontWeight:e["font-weight"]},i=Object.keys(t);i.every(e=>["color","fontFamily","fontSize","fontWeight"].includes(e))&&i.forEach(e=>{t[e]&&(this._getInput().style[e]=t[e]||"")})}_configureInput(){this._getInput().autocomplete="cc-name",this._getInput().id=kc.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 tn(this._input,()=>new nn(Xi.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 Lc;!function(e){e.PRODUCTION="https://pay.bluesnap.com/web-sdk/5/bluesnap.js",e.SANDBOX="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"}(Lc||(Lc={}));class Bc{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e=!1){return t=this,i=void 0,r=function*(){if(this._window.bluesnap)return this._window.bluesnap;if(yield this._scriptLoader.loadScript(e?Lc.SANDBOX:Lc.PRODUCTION),!this._window.bluesnap)throw new pn;return this._window.bluesnap},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}const jc=Rt(e=>new Mc(new Bc(a()),e,new xc(new Rc,new Fc),new Cc),[{id:"credit_card",gateway:"bluesnapdirect"}]);class Uc{constructor(e){this._paymentIntegrationService=e}execute(e){return t=this,i=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 i=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();i=`${i}&${e}`}return new Promise(()=>window.location.replace(i))}return Promise.reject(e)}},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new vd)}deinitialize(){return Promise.resolve()}_formatePaymentPayload({payment:e}){if(!e)throw new oo(["payment"]);return e.paymentData&&gd(e.paymentData)&&_d(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}}}):(i=e.paymentData,Boolean("object"==typeof i&&null!==i&&"iban"in i&&"firstName"in i&&"lastName"in i&&"shopperPermission"in i)?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,i}_isBlueSnapDirectRedirectResponse(e){var t;if("object"!=typeof e||null===e)return!1;const i=e;if(!i.body)return!1;const n=i.body;return"additional_action_required"===n.status&&!!(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}}const qc=Rt(e=>new Uc(e),[{gateway:"bluesnapdirect"}]);var Vc;!function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(Vc||(Vc={}));const Gc=Vc;var Hc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class $c{constructor(e){this._paymentIntegrationService=e}execute(e,t){return Hc(this,void 0,void 0,function*(){const{payment:i}=e;if(!i)throw new oo(["payment"]);if(!this._initializeOptions)throw new nn(Xi.PaymentNotInitialized);const{onLoad:n,style:r}=this._initializeOptions,o=this._createIframe("bluesnapv2_hosted_payment_page",r),a=new Pi(new Promise(V));n(o,()=>a.cancel(new Vn)),yield this._paymentIntegrationService.submitOrder(e,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:i.methodId,gatewayId:i.gatewayId,shouldSaveInstrument:!1,target:o.name,promise:a.promise})})}finalize(e){return Hc(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),i=t.getOrder(),n=t.getPaymentStatus();if(!i||n!==Gc.ACKNOWLEDGE&&n!==Gc.FINALIZE)return Promise.reject(new vd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(e){return Hc(this,void 0,void 0,function*(){this._initializeOptions=e&&e.bluesnapv2,yield Promise.resolve()})}deinitialize(){return Promise.resolve()}_createIframe(e,t){const i=document.createElement("iframe");if(i.setAttribute("sandbox","allow-top-navigation allow-scripts allow-forms allow-same-origin"),i.name=e,t){const{border:e,height:n,width:r}=t;i.style.border=null!=e?e:"",i.style.height=null!=n?n:"",i.style.width=null!=r?r:""}return i}}const Wc=Rt(e=>new $c(e),[{gateway:"bluesnapv2"}]);class Yc{constructor(e){this.storage=e}saveExtraItemsData(e,t){const i=[...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(i)),i}catch(e){return{}}}readExtraItemsData(e){try{const t=this.storage.getItem(this.getStorageKey(e));if(!t)return null;const i=JSON.parse(t);return function(e){if(!D(e))return!1;const t=Object.values(e).some(e=>!D(e)||!("brand"in e)||!("category"in e));return Boolean(!t)}(i)?i:null}catch(e){return null}}clearExtraItemData(e){try{this.storage.removeItem(this.getStorageKey(e))}catch(e){}}getStorageKey(e){return e?`ORDER_ITEMS_${e}`:""}}function Kc(e){return Boolean(e.hasOwnProperty("analytics"))}function Jc(e){return"object"==typeof e&&null!==e&&"shouldCreateAccount"in e}class Zc extends Ji{constructor(e){super(),this.errorCode=e,this.name="BoltPaymentsFieldError",this.type="bolt_payments_field_error",this.body={errors:[Zc.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 Xc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Qc{constructor(e,t,i){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.analyticsExtraItemsManager=i,this.useBoltClient=!1,this.useBoltEmbedded=!1}initialize(e){return Xc(this,void 0,void 0,function*(){const{bolt:t,methodId:i}=e,{containerId:n,onPaymentSelect:r,useBigCommerceCheckout:o}=t||{};if(!i)throw new gn('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 Qi(Zi.MissingPaymentMethod);if(this.boltClient=yield this.boltScriptLoader.loadBoltClient(c,h,l),this.useBoltClient=!u,this.useBoltEmbedded=!!u,this.useBoltEmbedded){if(!n)throw new gn('Unable to initialize payment because "options.bolt.containerId" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.bolt.onPaymentSelect" argument is not provided.');this.boltEmbedded=yield this.boltScriptLoader.loadBoltEmbedded(c,h,l),this.mountBoltEmbeddedField(n),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 vd)}execute(e,t){return Xc(this,void 0,void 0,function*(){this.setExtraItemsForAnalytics();const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{methodId:r,paymentData:o}=i||{};let a;if(!e.payment)throw new oo(["payment"]);if(!r)throw new Qi(Zi.MissingPaymentMethod);if(!o||!function(e){return Boolean(D(e)&&("shouldSaveInstrument"in e||"nonce"in e||Jc(e)))}(o))throw new Qi(Zi.MissingPayment);yield this.paymentIntegrationService.submitOrder(n,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,i){return Xc(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e,i);const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(e).clientToken,{isStoreCreditApplied:o}=n.getCheckoutOrThrow(),{shouldSaveInstrument:a}=t,s=this.getBoltClientOrThrow();if(yield this.paymentIntegrationService.applyStoreCredit(o),!r)throw new Qi(Zi.MissingPaymentMethod);const d=yield new Promise((e,t)=>{const i={success:(i,n)=>{i.reference?e(i):t(new Kr("Unable to proceed because transaction reference is unavailable. Please try again later.")),n()},close:()=>{t(new Vn)}};s.configure({orderToken:r},{},i).open()});return{methodId:e,paymentData:{nonce:d.reference,shouldSaveInstrument:a}}})}getBoltEmbeddedPaymentPayload(e,t){var i;return Xc(this,void 0,void 0,function*(){if(!Jc(t))throw new Qi(Zi.MissingPayment);const n=this.validateTokenizeResultOrThrow(yield null===(i=this.embeddedField)||void 0===i?void 0:i.tokenize());return{methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:n.token,last_four_digits:n.last4,iin:n.bin,expiration_month:+n.expiration.split("-")[1],expiration_year:+n.expiration.split("-")[0]},provider_data:{create_account:!!t.shouldCreateAccount,embedded_checkout:!0}}}}})}getBoltFullCheckoutPaymentPayload(e,t){return Xc(this,void 0,void 0,function*(){yield this.setBoltOrderId();const i=this.getBoltClientOrThrow(),n=yield i.getTransactionReference();if(!n)throw new Jr;return{methodId:e,paymentData:Object.assign(Object.assign({},t),{nonce:n})}})}getBoltClientOrThrow(){if(!this.boltClient)throw new nn(Xi.PaymentNotInitialized);return this.boltClient}getBoltEmbeddedOrThrow(){if(!this.boltEmbedded)throw new nn(Xi.PaymentNotInitialized);return this.boltEmbedded}hasBoltAccount(){return Xc(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),i=e.getBillingAddress(),n=(null==t?void 0:t.email)||(null==i?void 0:i.email)||"",r=this.getBoltClientOrThrow();try{return yield r.hasBoltAccount(n)}catch(e){throw new Jr}})}setBoltOrderId(){return Xc(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 Jr}})}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 Jr;if(e instanceof Error)throw new Zc(e.message);const{token:t,last4:i,bin:n,expiration:r}=e,o=+i,a=+n,s=+`${r}`.split("-")[1],d=+`${r}`.split("-")[0];if(!t||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(s)||Number.isNaN(d))throw new oo;return e}setExtraItemsForAnalytics(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfigOrThrow(),i=e.getCartOrThrow();if(t.checkoutSettings.isAnalyticsEnabled&&Kc(window)){const{id:e,lineItems:t}=i;this.analyticsExtraItemsManager.saveExtraItemsData(e,t)}}}const el=Rt(e=>new Qc(e,new no(a()),new Yc(Te)),[{id:"bolt"}]);function tl(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var il=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class nl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeSdk=t}initialize(e){return il(this,void 0,void 0,function*(){const{methodId:t,braintreeach:i}=e||{};if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');this.getMandateText=null==i?void 0:i.getMandateText,yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{clientToken:r,initializationData:o}=n;if(!r||!o)throw new Qi(Zi.MissingPaymentMethod);this.braintreeSdk.initialize(r);try{this.usBankAccount=yield this.braintreeSdk.getUsBankAccount()}catch(e){this.handleBraintreeError(e)}})}execute(e,t){return il(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const r=gd(i.paymentData||{}),o=r?yield this.tokenizePaymentForVaultedInstrument(i):yield this.tokenizePayment(i),a=r?yield this.preparePaymentDataForVaultedInstrument(o,i):yield this.preparePaymentData(o,i);yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new vd)}deinitialize(){return il(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}tokenizePayment({paymentData:e}){return il(this,void 0,void 0,function*(){const t=this.getUsBankAccountOrThrow();if(!tl(e))throw new oo(["payment.paymentData"]);const i=gd(e)?"The data are used for stored instrument verification":"function"==typeof this.getMandateText&&this.getMandateText();if(!i)throw new gn("Unable to proceed because getMandateText is not provided or returned undefined value.");try{const{nonce:n}=yield t.tokenize({bankDetails:this.getBankDetails(e),mandateText:i});return n}catch(e){this.handleBraintreeError(e)}})}tokenizePaymentForVaultedInstrument(e){return il(this,void 0,void 0,function*(){const{methodId:t,paymentData:i={}}=e,n=this.paymentIntegrationService.getState(),{config:r}=n.getPaymentMethodOrThrow(t);if(!r.isVaultingEnabled)throw new gn("Vaulting is disabled but a vaulted instrument was being used for this transaction");return tl(i)?this.tokenizePayment(e):null})}preparePaymentData(e,t){return il(this,void 0,void 0,function*(){const{methodId:i,paymentData:n={}}=t;if(!tl(n))throw new oo(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,routingNumber:s,accountNumber:d}=n;return{methodId:i,paymentData:{deviceSessionId:r,shouldSetAsDefaultInstrument:a,shouldSaveInstrument:o,formattedPayload:{tokenized_bank_account:{issuer:s,masked_account_number:d.substr(-4),token:e}}}}})}preparePaymentDataForVaultedInstrument(e,t){return il(this,void 0,void 0,function*(){const{methodId:i,paymentData:n={}}=t;if(!gd(n)||!_d(n))throw new oo(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{instrumentId:o,shouldSetAsDefaultInstrument:a}=n;return{methodId:i,paymentData:Object.assign({deviceSessionId:r,instrumentId:o,shouldSetAsDefaultInstrument:a},e&&{nonce:e})}})}getBankDetails(e){const t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i=e.ownershipType.toLowerCase(),n=e.accountType.toLowerCase();return Object.assign(Object.assign({accountNumber:e.accountNumber,routingNumber:e.routingNumber,ownershipType:i},"personal"===i?{firstName:e.firstName,lastName:e.lastName}:{businessName:e.businessName}),{accountType:n,billingAddress:{streetAddress:t.address1,extendedAddress:t.address2,locality:t.city,region:t.stateOrProvinceCode,postalCode:t.postalCode}})}getUsBankAccountOrThrow(){if(!this.usBankAccount)throw new nn(Xi.PaymentNotInitialized);return this.usBankAccount}handleBraintreeError(e){if(!zn(e))throw e;throw new Kr(e.message)}}const rl=Rt(e=>new nl(e,(e=>{const t=new bn(e),i=new qn(a(),window,t);return new Ln(i)})(e)),[{id:"braintreeach"}]);class ol{constructor(e){this.paymentIntegrationService=e,this.braintreeHostWindow=window}render(e,t,i){const n=t&&document.getElementById(t);if(this.braintreeHostWindow.paypal&&n){const r=this.paymentIntegrationService.getState(),o=r.getCartOrThrow(),a=r.getBillingAddressOrThrow(),s=r.getPaymentMethodOrThrow(e);if(!s.initializationData)return;const{paypalBNPLConfiguration:d=[]}=s.initializationData,c=i===yo.PAYMENT?"checkout":i,l=d&&d.find(({id:e})=>e===c);if(!l||!l.status)return;i===yo.CART&&(n.removeAttribute("data-pp-style-logo-type"),n.removeAttribute("data-pp-style-logo-position"),n.removeAttribute("data-pp-style-text-color"),n.removeAttribute("data-pp-style-text-size")),this.braintreeHostWindow.paypal.Messages({amount:o.cartAmount,buyerCountry:a.countryCode,placement:i,style:this.getPaypalMessagesStylesFromBNPLConfig(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 al{constructor(e){const{element:t,closeElement:i,mainElement:n}=this._createElements(e);this._element=t,this._closeElement=i,this._mainElement=n}show(e){this._mainElement.parentElement||(this._registerClick(e),document.body.appendChild(this._mainElement),setTimeout(()=>this._element.style.opacity="1"))}remove(){this._mainElement.parentElement&&(this._unregisterClick&&this._unregisterClick(),this._removeAfterTransition(),setTimeout(()=>this._element.style.opacity="0"))}_createElements(e){const t=document.createElement("div"),{background:i="rgba(0, 0, 0, 0.8)",id:n="checkoutOverlay",transitionDuration:r=400,hasCloseButton:o=!1,innerHtml:a=null}=e||{};let s,d,c,l,u=t;if(n&&(t.id=n),a){const e=document.createElement("div");l=`${n}--overlayText`,e.className=l,e.appendChild(a),t.appendChild(e)}return o&&(c=`${n}--close`,s=document.createElement("div"),s.className=c,d=`${n}--layout`,u=document.createElement("div"),u.className=d,u.appendChild(t),u.appendChild(s)),u.appendChild(function(e){const{id:t,background:i,transitionDuration:n,classLayout:r,classOverlayText:o,classClose:a}=e,s=document.createElement("style"),d=r?`, .${r}`:"";return s.id=`${t}--styles`,s.type="text/css",s.innerText=`\n #${t}${d} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${t} {\n transition: opacity ${n}ms ease-out;\n background: ${i};\n opacity: 0;\n }\n `,o&&(s.innerText+=`\n #${t} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${t} .${o} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `),a&&(s.innerText+=`\n #${t} {\n opacity: 1;\n }\n .${r} .${a} {\n position: fixed;\n right: 16px;\n top: 16px;\n width: 16px;\n height: 16px;\n opacity: 0.6;\n cursor: pointer;\n z-index: 3147483647;\n }\n .${r} .${a}::after, .${r} .${a}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${r} .${a}::after {\n transform: rotate(-45deg);\n }\n .${r} .${a}::before {\n transform: rotate(45deg);\n }\n `),s}({id:n,background:i,transitionDuration:r,classLayout:d,classOverlayText: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:i}=e;this._addEventListener(this._element,t),this._addEventListener(this._closeElement,i),this._unregisterClick=()=>{this._removeEventListener(this._element,t),this._removeEventListener(this._closeElement,i),this._unregisterClick=void 0}}}_removeAfterTransition(){const e=t=>{"opacity"===t.propertyName&&(this._mainElement.parentElement&&this._mainElement.remove(),this._element.removeEventListener("transitionend",e))};this._element.addEventListener("transitionend",e)}}const sl={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};function dl(e){return"object"==typeof e&&null!==e&&"name"in e&&"BraintreeError"===e.name}function cl(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 ll=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ul{constructor(e,t,i,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeMessages=i,this.loadingIndicator=n,this.braintreeHostWindow=window}initialize(e){return ll(this,void 0,void 0,function*(){const{braintree:t,methodId:i}=e;if(this.braintree=t,this.paymentMethod&&this.paymentMethod.nonce||(this.paymentMethod=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i)),this.paymentMethod.clientToken&&(null==t?void 0:t.bannerContainerId))return yield this.loadPaypal(),this.loadPaypalCheckoutInstance();if(this.paymentMethod.clientToken)return this.loadPaypal();const n=yield this.paymentIntegrationService.loadPaymentMethod(i);if(this.paymentMethod=n.getPaymentMethodOrThrow(i),null==t?void 0:t.bannerContainerId)return this.loadPaypalCheckoutInstance();if(!this.paymentMethod.clientToken)throw new Qi(Zi.MissingPaymentMethod);return this.loadPaypal()})}execute(e,t){var i;return ll(this,void 0,void 0,function*(){const{payment:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{onError:o}=this.braintree||{};if(!n)throw new oo(["payment"]);try{const e=yield this.preparePaymentData(n,r.useStoreCredit);yield this.paymentIntegrationService.submitOrder(r,t),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.isProviderError(e)&&(yield this.loadPaypal(),null===(i=this.paypalButtonRender)||void 0===i||i.close(),yield this.loadPaypalCheckoutInstance(),yield new Promise((e,t)=>{o&&"function"==typeof o&&o(new Error("INSTRUMENT_DECLINED")),t()})),this.handleError(e)}})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;return this.braintreeTokenizePayload=void 0,null===(e=this.paypalButtonRender)||void 0===e||e.close(),this.braintreeIntegrationService.teardown()}preparePaymentData(e,t){var i;return ll(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),r=n.getOutstandingBalance(t),o=n.getStoreConfig();if(!r)throw new Qi(Zi.MissingCheckout);if(!o)throw new Qi(Zi.MissingCheckoutConfig);if(!this.paymentMethod)throw new nn(Xi.PaymentNotInitialized);const{currency:a,storeProfile:{storeLanguage:s}}=o,{nonce:d,config:{isVaultingEnabled:c}}=this.paymentMethod,{methodId:l,paymentData:u={}}=e,h=(null===(i=this.braintreeTokenizePayload)||void 0===i?void 0:i.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(gd(u)||(p=u,Boolean(p.instrumentId)&&!Object.prototype.hasOwnProperty.call(p,"ccNumber")&&!Object.prototype.hasOwnProperty.call(p,"ccCvv"))){if(!c)throw new gn("Vaulting is disabled but a vaulted instrument was being used for this transaction");return Promise.resolve(e)}var p;if(!_d(u))throw new Qi(Zi.MissingPayment);const{shouldSaveInstrument:m,shouldSetAsDefaultInstrument:y}=u;if(m&&!c)throw new gn("Vaulting is disabled but shouldSaveInstrument is set to true");const g=n.getShippingAddress(),v=g?cl(g):void 0;return Promise.all([this.braintreeIntegrationService.paypal({amount:r,locale:s,currency:a.code,offerCredit:"braintreepaypalcredit"===this.paymentMethod.id,shippingAddressOverride:v,shouldSaveInstrument:m||!1,shippingAddressEditable:!1}),this.braintreeIntegrationService.getSessionId()]).then(([{nonce:t,details:i}={},n])=>Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(t,i&&i.email,n,m,y)}))})}formattedPayload(e,t,i,n,r){return{formattedPayload:{vault_payment_instrument:n||null,set_as_default_stored_instrument:r||null,device_info:i||null,paypal_account:{token:e,email:t||null}}}}loadPaypalCheckoutInstance(){return ll(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t,id:i}=this.paymentMethod||{};if(!e)throw new Qi(Zi.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e);const n={currency:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,intent:null==t?void 0:t.intent,isCreditEnabled:null==t?void 0:t.isCreditEnabled},r="braintreepaypalcredit"===i||!(null==t?void 0:t.isCreditEnabled);yield this.braintreeIntegrationService.getPaypalCheckout(n,e=>{var t;r&&i&&(null===(t=this.braintree)||void 0===t?void 0:t.bannerContainerId)&&this.renderPayPalMessages(i,this.braintree.bannerContainerId),this.renderPayPalButton(e)},this.handleError)}catch(e){this.handleError(e)}})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,yo.PAYMENT)}renderPayPalButton(e){const{onPaymentError:t,submitForm:i,onRenderButton:n,containerId:r,onError:o}=this.braintree||{};if(!r)return;if(!this.paymentMethod)throw new nn(Xi.PaymentNotInitialized);this.loadingIndicatorContainer=r.split("#")[1];const{id:a,config:{testMode:s}}=this.paymentMethod,{paypal:d}=this.braintreeHostWindow,c=null==d?void 0:d.FUNDING.PAYPAL;d&&c?(this.paypalButtonRender=d.Buttons({env:s?"sandbox":"production",commit:!1,fundingSource:c,onClick:()=>{this.toggleLoadingIndicator(!0)},createOrder:()=>this.setupPayment(e,a,t),onApprove:t=>ll(this,void 0,void 0,function*(){this.braintreeTokenizePayload=yield this.tokenizePaymentOrThrow(t,e),i&&"function"==typeof i&&i()}),onCancel:()=>{this.toggleLoadingIndicator(!1)},onError:e=>{this.toggleLoadingIndicator(!1),null==o||o(e)}}),n&&"function"==typeof n&&n(),this.paypalButtonRender.isEligible()&&this.paypalButtonRender.render(`${r}`)):this.removeElement(r.split("#")[1])}setupPayment(e,t,i){return ll(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState();try{const i=n.getCustomer(),r=n.getPaymentMethodOrThrow(t),o=n.getCheckoutOrThrow().outstandingBalance,a=n.getStoreConfigOrThrow().currency.code,s=n.getShippingAddress()||(null==i?void 0:i.addresses[0]),d=s?cl(s):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:d,amount:o,currency:a,offerCredit:!1,intent:r.initializationData.intent})}catch(e){throw i&&(dl(e)||e instanceof Ji)&&i(e),e}})}tokenizePaymentOrThrow(e,t,i){return ll(this,void 0,void 0,function*(){try{return yield t.tokenizePayment(e)}catch(e){throw i&&(dl(e)||e instanceof Ji)&&i(e),e}})}loadPaypal(){return ll(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t}=this.paymentMethod||{};if(!e||!t)throw new Qi(Zi.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e),yield this.braintreeIntegrationService.getPaypal()}catch(e){this.handleError(e)}return Promise.resolve()})}handleError(e){if(!dl(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Vn(e.message);throw new Kr(e.message)}isProviderError(e){var t,i,n;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"2046"===(null===(n=null===(i=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===i?void 0:i.provider_error)||void 0===n?void 0:n.code)}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const hl=Rt(e=>{const t=window,i=new al,n=new bn(e),r=new vo(new qn(a(),t,n),t,i),o=new ol(e);return new ul(e,r,o,new td({containerStyles:sl}))},[{id:"braintreepaypal"},{id:"braintreepaypalcredit"}]);class pl{constructor(e){this.requestSender=e}getOrderStatus(e="braintreelocalmethods",t){return i=this,n=void 0,o=function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}var ml=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class yl{constructor(e,t,i,n,r=3e3,o=3e5){this.paymentIntegrationService=e,this.braintreeSdk=t,this.braintreeRequestSender=i,this.loadingIndicator=n,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.isLPMsUpdateExperimentEnabled=!1,this.pollingTimer=0,this.stopPolling=V,this.isPollingEnabled=!1}initialize(e){return ml(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,braintreelocalmethods:n}=e;if(this.gatewayId=t,!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');this.braintreelocalmethods=n,this.loadingIndicatorContainer=n.container.split("#")[1],yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(t),{clientToken:a,config:s,initializationData:d}=o,c=r.getStoreConfigOrThrow().checkoutSettings.features;if(this.isPollingEnabled=Wt(c,"PAYPAL-5258.braintree_local_methods_polling"),this.isLPMsUpdateExperimentEnabled=Wt(c,"PAYPAL-4853.add_new_payment_flow_for_braintree_lpms"),!a||!d||!s.merchantId)throw new Qi(Zi.MissingPaymentMethod);try{this.braintreeSdk.initialize(a),this.isNonInstantPaymentMethod(i)||(this.braintreeLocalPayment=yield this.braintreeSdk.getBraintreeLocalPayment(s.merchantId))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new vd)}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:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{methodId:r}=i;this.toggleLoadingIndicator(!0),this.isNonInstantPaymentMethod(r)?yield this.executeWithNotInstantLPM(r):yield this.executeWithInstantLPM(r,n,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,i)=>{window.location.replace(t),this.toggleLoadingIndicator(!1),i()})}return this.handleError(e),Promise.reject(e)}})}executeWithInstantLPM(e,t,i){return ml(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment)throw new Jr;yield new Promise((n,r)=>{var o;null===(o=this.braintreeLocalPayment)||void 0===o||o.startPayment(this.getInstantLPMConfig(e,t,i),this.getInstantLPMCallback(n,r,e,t,i))})})}getLPMsBasicPaymentData(){return ml(this,void 0,void 0,function*(){const{deviceData:e}=yield this.braintreeSdk.getDataCollectorOrThrow();return{deviceSessionId:e}})}getInstantLPMConfig(e,t,i){const n=this.paymentIntegrationService.getState(),r=n.getCartOrThrow(),o=n.getBillingAddressOrThrow(),{firstName:a,lastName:s,countryCode:d}=o,{currency:c,email:l,lineItems:u}=r,h=u.physicalItems.length>0,p=n.getCheckoutOrThrow().outstandingBalance,m=n.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:(n,r)=>ml(this,void 0,void 0,function*(){if(!this.isLPMsUpdateExperimentEnabled)return this.orderId=n.paymentId,void r();const o=yield this.getLPMsBasicPaymentData(),a=Object.assign(Object.assign({},o),{formattedPayload:{method:e,[`${e}_account`]:{order_id:n.paymentId}}});try{yield this.paymentIntegrationService.submitOrder(t,i),yield this.paymentIntegrationService.submitPayment({methodId:e,paymentData:a})}catch(t){if(this.isBraintreeOrderSavedResponse(t)&&t.body.additional_action_required.data.order_id_saved_successfully)return r(),this.isPollingEnabled?new Promise((t,i)=>{this.initializePollingMechanism(e,t,i,this.gatewayId)}):void 0;throw t}})}}getInstantLPMCallback(e,t,i,n,r){const o=this.paymentIntegrationService.getState().getCartOrThrow();return(a,s)=>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 Jr));const d=yield this.getLPMsBasicPaymentData(),c=Object.assign(Object.assign({},d),{formattedPayload:{method:i,[`${i}_account`]:Object.assign({email:o.email,token:s.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId})}});try{return this.isLPMsUpdateExperimentEnabled||(yield this.paymentIntegrationService.submitOrder(n,r)),yield this.paymentIntegrationService.submitPayment({methodId:i,paymentData: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 An}isBraintreeRedirectError(e){var t;if("object"!=typeof e||null===e)return!1;const{body:i}=e;return!!i&&!!(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}isBraintreeOrderSavedResponse(e){var t;if("object"!=typeof e||null===e)return!1;const{body:i}=e;return!!i&&(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.hasOwnProperty("order_id_saved_successfully"))}initializePollingMechanism(e,t,i,n){return ml(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.braintreeRequestSender.getOrderStatus(n,{params:{useMetadata:!1}}),o=r.status===En.Pending,a=r.status===En.Completed,s=r.status===En.Failed;if(a)return this.deinitializePollingMechanism(),t();if(s)return i();if(!a&&o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,braintreelocalmethods:this.braintreelocalmethods}),this.handleError(new rc)}catch(e){i()}})}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 gl=Rt(e=>{const t=window,n=new bn(e),r=new Ln(new qn(a(),t,n)),o=i(),s=new pl(o);return new yl(e,r,s,new td({styles:{backgroundColor:"black"}}))},[{gateway:"braintreelocalmethods"}]);function vl(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var fl=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Sl{constructor(e,t,i){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.braintreeSdk=i}initialize(e){var t;return fl(this,void 0,void 0,function*(){const{methodId:i,braintreefastlane:n}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.braintreefastlane" argument is not provided.');if(!n.onInit||"function"!=typeof n.onInit)throw new gn('Unable to initialize payment because "options.braintreefastlane.onInit" argument is not provided or it is not a function.');if(!n.onChange||"function"!=typeof n.onChange)throw new gn('Unable to initialize payment because "options.braintreefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(i),{initializationData:a,clientToken:s}=o||{},{isFastlaneStylingEnabled:d}=a||{},c=Wt(r.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");this.is3DSEnabled=o.config.is3dsEnabled,s&&c&&this.braintreeSdk.initialize(s);const l=Po(d?null===(t=o.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,n.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(i,l),this.shouldRunAuthenticationFlow()&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow()),yield this.initializeCardComponent(),this.onError=n.onError,n.onInit(e=>this.renderBraintreeCardComponent(e)),n.onChange(()=>this.handleBraintreeStoredInstrumentChange(i))})}execute(e,t){return fl(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);yield this.paymentIntegrationService.submitOrder(n,t);const r=yield this.preparePaymentPayload(i.methodId);yield this.paymentIntegrationService.submitPayment(r),this.braintreeFastlaneUtils.removeSessionIdFromCookies()})}finalize(){return Promise.reject(new vd)}deinitialize(){return fl(this,void 0,void 0,function*(){return this.braintreeCardComponent=void 0,Promise.resolve()})}initializeCardComponent(){return fl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),{phone:t,firstName:i,lastName:n}=e.getBillingAddressOrThrow(),r=`${i} ${n}`,o={styles:{},fields:Object.assign({cardholderName:{prefill:r,enabled:!0}},t&&{phoneNumber:{prefill:t}})},a=this.braintreeFastlaneUtils.getBraintreeFastlaneComponentOrThrow();this.braintreeCardComponent=yield a(o)})}renderBraintreeCardComponent(e){const t=this.getBraintreeCardComponentOrThrow();if(!e)throw new gn('Unable to initialize payment because "container" argument is not provided.');t.render(e)}preparePaymentPayload(e){var t,i;return fl(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),r=n.getBillingAddressOrThrow(),o=`${r.firstName} ${r.lastName}`,a=this.getPayPalInstruments()[0],s=yield this.braintreeFastlaneUtils.getDeviceSessionId(),d=Wt(n.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");if(a){const t=this.is3DSEnabled&&d?yield this.get3DS(a.bigpayToken,(null==a?void 0:a.iin)||""):void 0;return{methodId:e,paymentData:{deviceSessionId:s,formattedPayload:{paypal_fastlane_token:{token:t||a.bigpayToken}}}}}const{getPaymentToken:c}=this.getBraintreeCardComponentOrThrow(),l=yield c({name:{fullName:o},billingAddress:this.mapToPayPalAddress(r)}),u=(null===(i=null===(t=l.paymentSource.card)||void 0===t?void 0:t.binDetails)||void 0===i?void 0:i.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 fl(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=yield this.braintreeSdk.getBraintreeThreeDS(),r=i.getOrderOrThrow();return new Promise((i,o)=>{n.verifyCard({amount:null==r?void 0:r.orderAmount,nonce:e,bin:t,onLookupComplete:(e,t)=>{n.on("customer-canceled",()=>{"function"==typeof this.onError&&this.onError(new Vn),o(new Vn)}),t()}},(e,t)=>(e&&"THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT"===e.code&&("function"==typeof this.onError&&this.onError(new Vn),o(new Vn)),i(t.nonce)))})})}mapToPayPalAddress(e){return{streetAddress:(null==e?void 0:e.address1)||"",locality:(null==e?void 0:e.city)||"",region:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCodeAlpha2:(null==e?void 0:e.countryCode)||""}}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getCustomerOrThrow(),n=e.getPaymentProviderCustomer(),r=vl(n)?n:{},o=this.braintreeFastlaneUtils.getSessionIdFromCookies();return!(!i.isGuest||(null==r?void 0:r.authenticationState)===Tn.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}getBraintreeCardComponentOrThrow(){if(!this.braintreeCardComponent)throw new pn;return this.braintreeCardComponent}getPayPalInstruments(){const e=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow();return(vl(e)?e:{}).instruments||[]}handleBraintreeStoredInstrumentChange(e){return fl(this,void 0,void 0,function*(){const t=this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow(),{selectionChanged:i,selectedCard:n}=yield t.profile.showCardSelector();if(i){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),i=vl(t)?t:{},r=this.braintreeFastlaneUtils.mapPayPalToBcInstrument(e,[n]);if(r&&r.length>0)return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},i),{instruments:[...r]})),r[0]}})}}const wl=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t),r=new To(e,n),o=new qn(a(),t,i),s=new Ln(o);return new Sl(e,r,s)},[{id:"braintreeacceleratedcheckout"}]);var Il=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class _l{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i}initialize(e){return Il(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:i}=e;if(!t)throw new gn('Unable to initialize payment because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState();this.paymentMethod=n.getPaymentMethodOrThrow(i);const r=n.getCheckoutOrThrow(),o=n.getStoreConfigOrThrow(),{clientToken:a,config:s}=this.paymentMethod||{};if(!a)throw new Qi(Zi.MissingPaymentMethod);const{onError:d=V,onPaymentSelect:c=V}=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(i)])).then(()=>c()).catch(e=>d(e))),u.on("payment.error",(e,t)=>d(t))})}execute(e,t){var i,n;return Il(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!r)throw new gn('Unable to submit payment because "payload.payment" argument is not provided.');if(!(null===(n=null===(i=this.paymentMethod)||void 0===i?void 0:i.initializationData)||void 0===n?void 0:n.nonce))throw new Qi(Zi.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 vd)}deinitialize(){return Il(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}tokenizePayment(e,t){return Il(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(n),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}handleError(e){if(e instanceof Error&&"BraintreeError"===e.name)throw new Kr(e.message);throw e}}const Cl=Rt(e=>{const t=window,i=new bn(e),n=new Ln(new qn(a(),t,i));return new _l(e,Ee(),n)},[{id:"braintreevisacheckout"}]);var bl=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Pl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}initialize(e){return bl(this,void 0,void 0,function*(){const{methodId:t}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState();this.venmoOptions=e.braintreevenmo;const n=i.getPaymentMethodOrThrow(t);yield this.initializeBraintreeVenmo(n)})}execute(e){return bl(this,void 0,void 0,function*(){const{payment:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!t)throw new oo(["payment"]);try{const e=yield this.preparePaymentData(t);yield this.paymentIntegrationService.submitOrder(i),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new vd)}deinitialize(){return bl(this,void 0,void 0,function*(){return yield this.braintreeIntegrationService.teardown(),Promise.resolve()})}handleError(e){if(!zn(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Vn(e.message);throw new Kr(e.message)}initializeBraintreeVenmo(e){var t;return bl(this,void 0,void 0,function*(){const{clientToken:i}=e;if(!i)throw new Qi(Zi.MissingPaymentMethod);const n=Wt(this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features,"PAYPAL-5406.braintree_venmo_web_fallback_support");try{this.braintreeIntegrationService.initialize(i),this.braintreeVenmoCheckout=yield this.braintreeIntegrationService.getVenmoCheckout(Object.assign(Object.assign({},void 0!==(null===(t=this.venmoOptions)||void 0===t?void 0:t.allowDesktop)?{allowDesktop:this.venmoOptions.allowDesktop}:{}),n?{mobileWebFallBack:n}:{}))}catch(e){this.handleError(e)}})}preparePaymentData(e){return bl(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{nonce:i}=t.getPaymentMethodOrThrow(e.methodId);if(i)return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(i)});const n=yield this.braintreeVenmoTokenize(),r=yield this.braintreeIntegrationService.getSessionId();return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(n.nonce,n.details.email,r)})})}formattedPayload(e,t,i){return{formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:i||null,paypal_account:{token:e,email:t||null}}}}braintreeVenmoTokenize(){return new Promise((e,t)=>{var i;null===(i=this.braintreeVenmoCheckout)||void 0===i||i.tokenize((i,n)=>{if(i)return t(i);e(n)})})}}const Ol=Rt(e=>{const t=window,i=a(),n=new bn(e),r=new qn(i,t,n),o=new vo(r,t);return new Pl(e,o)},[{id:"braintreevenmo"}]);var El=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Al{constructor(e,t,i){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeHostedForm=i}initialize(e){return El(this,void 0,void 0,function*(){const{methodId:t,gatewayId:i,braintree:n}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState();this.paymentMethod=r.getPaymentMethodOrThrow(t);const{clientToken:o}=this.paymentMethod;if(!o)throw new Qi(Zi.MissingPaymentMethod);this.threeDSecure=null==n?void 0:n.threeDSecure,this.onPaymentError=null==n?void 0:n.onPaymentError;try{this.braintreeIntegrationService.initialize(o,this.threeDSecure),this.isHostedPaymentFormEnabled(t,i)&&(null==n?void 0:n.form)&&(yield this.braintreeHostedForm.initialize(n.form,n.unsupportedCardBrands,o),this.isHostedFormInitialized=this.braintreeHostedForm.isInitialized()),this.is3dsEnabled=this.paymentMethod.config.is3dsEnabled,this.deviceSessionId=yield this.braintreeIntegrationService.getSessionId(),this.shouldInitializeBraintreeFastlane()&&(yield this.initializeBraintreeFastlaneOrThrow(t))}catch(e){return this.handleError(e,t)}})}execute(e){return El(this,void 0,void 0,function*(){const{payment:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!t)throw new oo(["payment"]);this.isHostedFormInitialized&&this.braintreeHostedForm.validate(),yield this.paymentIntegrationService.submitOrder(i);const n=this.paymentIntegrationService.getState(),r=n.getBillingAddressOrThrow(),o=n.getOrderOrThrow().orderAmount;try{const e=this.isHostedFormInitialized?yield this.prepareHostedPaymentData(t,r,o):yield this.preparePaymentData(t,r,o);yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},t),{paymentData:e}))}catch(e){return this.processAdditionalAction(e,t,o)}})}finalize(){return Promise.reject(new vd)}deinitialize(){return El(this,void 0,void 0,function*(){return this.isHostedFormInitialized=!1,yield Promise.all([this.braintreeIntegrationService.teardown(),this.braintreeHostedForm.deinitialize()]),Promise.resolve()})}handleError(e,t){var i;if(dl(e)){if(!(t&&this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:t})||"HOSTED_FIELDS_INVALID_FIELD_SELECTOR"!==e.code))return;if(e.code.startsWith("THREEDS_"))return null===(i=this.onPaymentError)||void 0===i||i.call(this,new Kr("THREEDS_VERIFICATION_FAILED")),Promise.reject();throw new Kr(e.message)}throw e}preparePaymentData(e,t,i){return El(this,void 0,void 0,function*(){const{paymentData:n}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e))return Object.assign(Object.assign({},r),n);const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=_d(n)?n:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.braintreeIntegrationService.verifyCard(e,t,i):yield this.braintreeIntegrationService.tokenizeCard(e,t);return Object.assign(Object.assign({},r),{nonce:s,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})})}prepareHostedPaymentData(e,t,i){return El(this,void 0,void 0,function*(){const{paymentData:n}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e)){const{nonce:e}=yield this.braintreeHostedForm.tokenizeForStoredCardVerification();return Object.assign(Object.assign(Object.assign({},r),n),{nonce:e})}const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=_d(n)?n:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.verifyCardWithHostedForm(t,i):yield this.braintreeHostedForm.tokenize(t);return Object.assign(Object.assign({},r),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,nonce:s})})}prepareAdditionalActionPaymentData(e,t){const{paymentData:i}=e,n={deviceSessionId:this.deviceSessionId,nonce:t},{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=_d(i)?i:{};return this.isSubmittingWithStoredCard(e)&&(r||o)?Object.assign(Object.assign({},i),n):Object.assign({},n)}verifyCardWithHostedForm(e,t){return El(this,void 0,void 0,function*(){const i=yield this.braintreeHostedForm.tokenize(e);return this.braintreeIntegrationService.challenge3DSVerification(i,t)})}processAdditionalAction(e,t,i){return El(this,void 0,void 0,function*(){if(!ca(e)||!Z(e.body.errors,{code:"three_d_secure_required"}))return this.handleError(e);try{const{payer_auth_request:n}=function(e){return"object"==typeof e&&null!==e&&"name"in e&&"body"in e&&"status"in e.body&&"three_ds_result"in e.body&&"payer_auth_request"in e.body.three_ds_result&&"errors"in e.body}(e)&&e.body.three_ds_result||{},{paymentData:r}=t,o=this.paymentIntegrationService.getState();if(!r||!gd(r))throw new oo(["instrumentId"]);const a=o.getCardInstrumentOrThrow(r.instrumentId),{nonce:s}=yield this.braintreeIntegrationService.challenge3DSVerification({nonce:n||"",bin:a.iin},i),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||!gd(e.paymentData))}shouldPerform3DSVerification(e){return!(!this.is3dsEnabled||this.isSubmittingWithStoredCard(e))}shouldInitializeBraintreeFastlane(){var e;const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),i=vl(t)?t:{};return(null===(e=this.paymentMethod)||void 0===e?void 0:e.initializationData.isAcceleratedCheckoutEnabled)&&!(null==i?void 0:i.authenticationState)}initializeBraintreeFastlaneOrThrow(e){return El(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getPaymentMethodOrThrow(e),{clientToken:r,config:o}=n;if(!r)throw new Qi(Zi.MissingPaymentMethod);this.braintreeIntegrationService.initialize(r,this.threeDSecure),yield this.braintreeIntegrationService.getBraintreeFastlane(i.id,o.testMode)})}}function Tl(e){return"cardNumber"in e}function kl(e){if(!zn(e))return!1;const{details:t}=e;return void 0===t||"object"==typeof t&&null!==t&&void 0===t.invalidFieldKeys||(i=t,Array.isArray(i)&&i.every(e=>"string"==typeof e));var i}var Dl,Ml=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e[e.CreditCard=0]="CreditCard",e[e.StoredCardVerification=1]="StoredCardVerification"}(Dl||(Dl={}));class zl{constructor(e,t){this.braintreeScriptLoader=e,this.braintreeSDKVersionManager=t,this.isInitializedHostedForm=!1,this.handleBlur=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onBlur)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy),errors:this.mapErrors(e.fields)})},this.handleFocus=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onFocus)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleCardTypeChange=e=>{var t,i;const n=1===e.cards.length?e.cards[0].type.replace(/^master-card$/,"mastercard"):void 0;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onCardTypeChange)||void 0===i||i.call(t,{cardType:n})},this.handleInputSubmitRequest=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onEnter)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleValidityChange=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===i||i.call(t,{isValid:this.isValidForm(e),errors:this.mapValidationErrors(e.fields)})}}initialize(e,t,i){var n,r,o,a,s;return Ml(this,void 0,void 0,function*(){this.clientToken=i,this.formOptions=e,this.type=Tl(e.fields)?Dl.CreditCard:Dl.StoredCardVerification;const d=this.mapFieldOptions(e.fields,t);E(d)?this.isInitializedHostedForm=!1:(this.cardFields=yield this.createHostedFields({fields:d,styles:e.styles&&this.mapStyleOptions(e.styles)}),null===(n=this.cardFields)||void 0===n||n.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 Ml(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 nn(Xi.PaymentNotInitialized);const e=this.cardFields.getState();if(!this.isValidForm(e)){this.handleValidityChange(e);const t=this.mapValidationErrors(e.fields);throw new ao(t)}}tokenize(e){var t,i,n,r,o;return Ml(this,void 0,void 0,function*(){if(!this.cardFields)throw new nn(Xi.PaymentNotInitialized);try{const r=yield this.cardFields.tokenize(H({billingAddress:e&&this.mapBillingAddress(e)},k));return null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===i||i.call(t,{isValid:!0,errors:{}}),{nonce:r.nonce,bin:null===(n=r.details)||void 0===n?void 0:n.bin}}catch(e){if(kl(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 ao(t)}throw e}})}tokenizeForStoredCardVerification(){var e,t,i,n,r;return Ml(this,void 0,void 0,function*(){if(!this.cardFields)throw new nn(Xi.PaymentNotInitialized);try{const n=yield this.cardFields.tokenize();return null===(t=null===(e=this.formOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,{isValid:!0,errors:{}}),{nonce:n.nonce,bin:null===(i=n.details)||void 0===i?void 0:i.bin}}catch(e){if(kl(e)){const t=this.mapTokenizeError(e,!0);if(t)throw null===(r=null===(n=this.formOptions)||void 0===n?void 0:n.onValidate)||void 0===r||r.call(n,{isValid:!1,errors:t}),new ao(t)}throw e}})}createHostedFields(e){return Ml(this,void 0,void 0,function*(){const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadHostedFields(),n=this.braintreeSDKVersionManager.getSDKVersion()===In?Object.assign(Object.assign({},e),{preventCursorJumps:!0}):e;return i.create(Object.assign(Object.assign({},n),{client:t}))})}getClient(){return Ml(this,void 0,void 0,function*(){if(!this.clientToken)throw new nn(Xi.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(Tl(e)){const i={};return null==t||t.forEach(e=>{(e=>Object.values(Mn).includes(e))(e)&&(i[e]=!1)}),H({number:Object.assign({container:`#${e.cardNumber.containerId}`,placeholder:e.cardNumber.placeholder,internalLabel:e.cardNumber.accessibilityLabel},Object.keys(i).length>0?{supportedCardBrands:i}:{}),expirationDate:{container:`#${e.cardExpiry.containerId}`,placeholder:e.cardExpiry.placeholder,internalLabel:e.cardExpiry.accessibilityLabel},cvv:e.cardCode&&{container:`#${e.cardCode.containerId}`,placeholder:e.cardCode.placeholder,internalLabel:e.cardCode.accessibilityLabel},cardholderName:{container:`#${e.cardName.containerId}`,placeholder:e.cardName.placeholder,internalLabel:e.cardName.accessibilityLabel}},k)}return H({number:e.cardNumberVerification&&{container:`#${e.cardNumberVerification.containerId}`,placeholder:e.cardNumberVerification.placeholder},cvv:e.cardCodeVerification&&{container:`#${e.cardCodeVerification.containerId}`,placeholder:e.cardCodeVerification.placeholder}},k)}mapStyleOptions(e){const t=(e={})=>H({color:e.color,"font-family":e.fontFamily,"font-size":e.fontSize,"font-weight":e.fontWeight},k);return{input:t(e.default),".invalid":t(e.error),":focus":t(e.focus)}}mapFieldType(e){switch(e){case"number":return this.type===Dl.StoredCardVerification?Fn.CardNumberVerification:Fn.CardNumber;case"expirationDate":return Fn.CardExpiry;case"cvv":return this.type===Dl.StoredCardVerification?Fn.CardCodeVerification:Fn.CardCode;case"cardholderName":return Fn.CardName;default:throw new Error("Unexpected field type")}}mapErrors(e){const t={};if(e)for(const[i,n]of Object.entries(e))if(n&&this.isValidParam(i)){const{isValid:e,isEmpty:r,isPotentiallyValid:o}=n;t[i]={isValid:e,isEmpty:r,isPotentiallyValid:o}}return t}mapValidationErrors(e){return Object.keys(e).reduce((t,i)=>{var n;return Object.assign(Object.assign({},t),{[this.mapFieldType(i)]:(null===(n=e[i])||void 0===n?void 0:n.isValid)?void 0:[this.createInvalidError(this.mapFieldType(i))]})},{})}mapTokenizeError(e,t=!1){var i,n;if("HOSTED_FIELDS_FIELDS_EMPTY"===e.code){const e=[this.createRequiredError(this.mapFieldType("cvv"))];return t?{[this.mapFieldType("cvv")]:e}:{[this.mapFieldType("cvv")]:e,[this.mapFieldType("expirationDate")]:[this.createRequiredError(this.mapFieldType("expirationDate"))],[this.mapFieldType("number")]:[this.createRequiredError(this.mapFieldType("number"))],[this.mapFieldType("cardholderName")]:[this.createRequiredError(this.mapFieldType("cardholderName"))]}}return null===(n=null===(i=e.details)||void 0===i?void 0:i.invalidFieldKeys)||void 0===n?void 0:n.reduce((e,t)=>{const i=this.mapFieldType(t);return Object.assign(Object.assign({},e),{[i]:[this.createInvalidError(i)]})},{})}createRequiredError(e){var t;return{fieldType:e,message:null!==(t={[Fn.CardCode]:"CVV is required",[Fn.CardCodeVerification]:"CVV is required",[Fn.CardNumber]:"Credit card number is required",[Fn.CardNumberVerification]:"Credit card number is required",[Fn.CardExpiry]:"Expiration date is required",[Fn.CardName]:"Full name is required"}[e])&&void 0!==t?t:"Field is required",type:"required"}}createInvalidError(e){var t,i,n,r;const o={[Fn.CardCode]:{message:"Invalid card code",type:"invalid_card_code"},[Fn.CardCodeVerification]:{message:"Invalid card code",type:"invalid_card_code"},[Fn.CardNumber]:{message:"Invalid card number",type:"invalid_card_number"},[Fn.CardNumberVerification]:{message:"Invalid card number",type:"invalid_card_number"},[Fn.CardExpiry]:{message:"Invalid card expiry",type:"invalid_card_expiry"},[Fn.CardName]:{message:"Invalid card name",type:"invalid_card_name"}};return{fieldType:e,message:null!==(i=null===(t=o[e])||void 0===t?void 0:t.message)&&void 0!==i?i:"Invalid field",type:null!==(r=null===(n=o[e])||void 0===n?void 0:n.type)&&void 0!==r?r:"invalid"}}isValidForm(e){return Object.keys(e.fields).every(t=>{var i;return null===(i=e.fields[t])||void 0===i?void 0:i.isValid})}isValidParam(e){return["number","cvv","expirationDate","postalCode","cardholderName","cardType"].includes(e)}}const Nl=Rt(e=>{const t=window,i=new bn(e),n=new qn(a(),t,i),r=new vo(n,t),o=new zl(n,i);return new Al(e,r,o)},[{id:"braintree"}]);var xl=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})},Fl=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i};class Rl{constructor(e){this._paymentIntegrationService=e}execute(e,t){var i,n;return this._isHostedPaymentFormEnabled(null===(i=e.payment)||void 0===i?void 0:i.methodId,null===(n=e.payment)||void 0===n?void 0:n.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,i=this._paymentIntegrationService.getState(),{paymentSettings:{bigpayBaseUrl:n=""}={}}=i.getStoreConfigOrThrow();if(!t)throw new gn;const r=this._paymentIntegrationService.createHostedForm(n,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 vd)}_executeWithoutHostedForm(e,t){return xl(this,void 0,void 0,function*(){const{payment:i}=e,n=Fl(e,["payment"]),r=i&&i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t),yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:r}))})}_executeWithHostedForm(e,t){return xl(this,void 0,void 0,function*(){const{payment:i}=e,n=Fl(e,["payment"]),r=this._hostedForm;if(!r)throw new nn(Xi.PaymentNotInitialized);if(!i||!i.methodId)throw new oo(["payment.methodId"]);yield this._paymentIntegrationService.submitOrder(n,t),yield r.validate().then(()=>r.submit(i))})}_isHostedPaymentFormEnabled(e,t){return!!e&&!0===this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!ne(e&&e.creditCard&&e.creditCard.form.fields).every(k)}}var Ll=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Bl extends Rl{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 Ll(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{methodId:i}=e;yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(i);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 Qi(Zi.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 nn(Xi.PaymentNotInitialized);if(!o||!s)throw new Qi(Zi.MissingPaymentMethod);if(this.sessionId=o,this.locale=n.getLocale(),!this.locale)throw new Qi(Zi.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 Kr("Failed to configure 3DS API.")},configuration:{userLanguage:this.locale,wsVersion:62}})}return Promise.resolve()})}execute(e,t){const i=Object.create(null,{execute:{get:()=>super.execute}});return Ll(this,void 0,void 0,function*(){const{payment:n}=e,r=n&&n.paymentData;if(!n||!r)throw new oo(["payment.paymentData"]);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n.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 i.execute.call(this,e,t).catch(e=>{if(!a||!ca(e)||!Z(e.body.errors,{code:"three_d_secure_required"}))return Promise.reject(e);const t=this.paymentIntegrationService.getState(),i=t.getOrder(),{storeProfile:{storeId:n}}=t.getStoreConfigOrThrow();if(!i||!this.sessionId)throw new Qi(Zi.MissingCheckout);const r=`${n}_${i.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 Qn;var o;const{three_ds_result:{token:s}}=e.body;return s?this.initiateAuthentication(r,s):Promise.reject(e)})})}finalize(e){return Ll(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===Gc.FINALIZE?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new vd)})}deinitialize(){return this.threeDSjs=void 0,this.sessionId="",super.deinitialize()}initiateAuthentication(e,t){return Ll(this,void 0,void 0,function*(){const i=yield new Promise((i,n)=>{if(!this.threeDSjs)throw new nn(Xi.PaymentNotInitialized);this.threeDSjs.initiateAuthentication(e,t,e=>{const t=e.error;return t?n(new Kr(t.msg)):this.threeDSjs&&"PROCEED"===e.gatewayRecommendation?i(e.restApiResponse):n(new Kr)})});if(i.transaction&&"AUTHENTICATION_AVAILABLE"===i.transaction.authenticationStatus)return this.authenticatePayer(e,t);throw new Kr})}authenticatePayer(e,t,i=1){return Ll(this,void 0,void 0,function*(){return new Promise((n,r)=>{if(!this.threeDSjs)return r(new nn(Xi.PaymentNotInitialized));this.threeDSjs.authenticatePayer(e,t,n=>Ll(this,void 0,void 0,function*(){const o=n.error;return o?o.cause&&"SERVER_BUSY"===o.cause&&i<5?(yield new Promise(e=>setTimeout(e,3e3)),this.authenticatePayer(e,t,++i)):r(new Kr):new Promise(V)}),{fullScreenRedirect:!0})})})}}class jl{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e){return t=this,i=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 pn;return this._window.ThreeDS},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}const Ul=Rt(e=>new Bl(e,new jl(a())),[{id:"cba_mpgs"}]);var ql;!function(e){e.OffsiteRedirect="offsite_redirect"}(ql||(ql={}));class Vl extends Rl{constructor(e){super(e),this.paymentIntegrationService=e}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===Gc.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new vd)}_executeWithHostedForm(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=this._hostedForm;if(!r)throw new nn(Xi.PaymentNotInitialized);if(!i||!i.methodId)throw new oo(["payment.methodId"]);try{yield r.validate(),yield this.paymentIntegrationService.submitOrder(n,t),yield r.submit(i)}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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_processResponse(e){if(!ca(e))return Promise.reject(e);const t=e.body.additional_action_required;return t&&t.type===ql.OffsiteRedirect?this._performRedirect(t):Promise.reject(e)}_performRedirect(e){return new Promise(()=>{window.location.replace(e.data.redirect_url)})}}class Gl extends Vl{_executeWithoutHostedForm(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=i&&i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_createFormattedPayload(e,t){if("fawry"===e&&"customerMobile"in t&&"customerEmail"in t){const e=t;return{customerMobile:e.customerMobile,customerEmail:e.customerEmail}}}}const Hl=Rt(e=>new Gl(e),[{gateway:"checkoutcom",id:"fawry"}]);function $l(e){return ca(e)&&Z(e.body.errors,{code:"three_d_secure_required"})}var Wl=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})},Yl=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i};class Kl extends Rl{constructor(e,t){super(e),this.paymentIntegrationService=e,this.formPoster=t}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===Gc.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new vd)}_executeWithoutHostedForm(e,t){return Wl(this,void 0,void 0,function*(){const{payment:i}=e,n=Yl(e,["payment"]),r=i&&i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this.paymentIntegrationService.submitOrder(n,t);try{yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:r}))}catch(e){return $l(e)?this._handleThreeDSecure(e):Promise.reject(e)}})}_executeWithHostedForm(e,t){return Wl(this,void 0,void 0,function*(){const{payment:i}=e,n=Yl(e,["payment"]),r=this._hostedForm;if(!r)throw new nn(Xi.PaymentNotInitialized);if(!i||!i.methodId)throw new oo(["payment.methodId"]);try{yield r.validate(),yield this.paymentIntegrationService.submitOrder(n,t),yield r.submit(i)}catch(e){return $l(e)?this._handleThreeDSecure(e):Promise.reject(e)}this.paymentIntegrationService.loadCurrentOrder()})}_handleThreeDSecure(e){const{acs_url:t,payer_auth_request:i,callback_url:n,merchant_data:r}=e.body.three_ds_result;return new Promise(()=>this.formPoster.postForm(t,{PaReq:i||null,TermUrl:n||null,MD:r||null}))}}const Jl=Rt(e=>new Kl(e,Ee()),[{gateway:"checkoutcom",id:"credit_card"},{gateway:"checkoutcom",id:"card"}]);class Zl extends Vl{_executeWithoutHostedForm(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=null==i?void 0:i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_createFormattedPayload(e,t){const i={iban:"",bic:""},{iban:n,bic:r}="iban"in t&&"bic"in t?t:i;return"sepa"===e&&document&&(i.iban=n,i.bic=r),i}}const Xl=Rt(e=>new Zl(e),[{gateway:"checkoutcom",id:"sepa"}]);class Ql extends Vl{_executeWithoutHostedForm(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=null==i?void 0:i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_createFormattedPayload(e,t){if("ideal"===e&&"bic"in t)return{bic:t.bic}}}const eu=Rt(e=>new Ql(e),[{gateway:"checkoutcom",id:"ideal"}]);const tu=["boleto","oxxo","qpay","ideal"];class iu extends Vl{_executeWithoutHostedForm(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=null==i?void 0:i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_createFormattedPayload(e,t){const i={ccDocument:""},n="ccDocument"in t?t.ccDocument:"";return-1!==tu.indexOf(e)&&n&&(i.ccDocument=n),i}}const nu=Rt(e=>new iu(e),[{gateway:"checkoutcom"}]);var ru=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ou{constructor(e,t){this._paymentIntegrationService=e,this._clearpayScriptLoader=t}initialize(e){return ru(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:t}=this._paymentIntegrationService.getState(),i=t(e.methodId,e.gatewayId),n=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features;this._clearpaySdk=yield this._clearpayScriptLoader.load(i,n)})}deinitialize(){return this._clearpaySdk=void 0,Promise.resolve()}execute(e,t){return ru(this,void 0,void 0,function*(){const{gatewayId:i,methodId:n}=e.payment||{};if(!i||!n)throw new oo(["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 gn("Unable to proceed because billing country is not supported.");return yield this._loadPaymentMethod(i,n,t),yield this._redirectToClearpay(a,this._paymentIntegrationService.getState().getPaymentMethod(n,i)),new Promise(V)})}finalize(e){var t,i,n;return ru(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new Qi(Zi.MissingCheckout);if(!a||!a.payment.token)throw new Qi(Zi.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(),ca(e))throw new Dd(null===(n=null===(i=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===i?void 0:i[0])||void 0===n?void 0:n.message)}})}_redirectToClearpay(e,t){return ru(this,void 0,void 0,function*(){if(!this._clearpaySdk||!t||!t.clientToken)throw new nn(Xi.PaymentNotInitialized);return this._clearpaySdk.initialize({countryCode:e}),this._clearpaySdk.redirect({token:t.clientToken}),Promise.resolve()})}_isCountrySupported(e){return"GB"===e}_loadPaymentMethod(e,t,i){var n;return ru(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},i),{params:Object.assign(Object.assign({},null==i?void 0:i.params),{method:t})}))}catch(e){if(e instanceof Qn&&422===(null===(n=e.body)||void 0===n?void 0:n.status))throw new gn("Clearpay can't process your payment for this order, please try another payment method");throw e}})}}class au{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t={}){return i=this,n=void 0,o=function*(){if(yield this._scriptLoader.loadScript(this._getScriptUrl(e.config.testMode,t)),!this._window.AfterPay)throw new pn;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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_getScriptUrl(e,t={}){const i=Wt(t,"PI-4555.clearpay_add_https_to_prod_script",!1);return e?i?"https://portal.sandbox.clearpay.co.uk/afterpay-async.js":"//portal.sandbox.clearpay.co.uk/afterpay-async.js":i?"https://portal.clearpay.co.uk/afterpay-async.js":"//portal.clearpay.co.uk/afterpay-async.js"}}const su=Rt(e=>new ou(e,new au(a())),[{gateway:"clearpay"},{id:"clearpay"}]),du=Rt(e=>new Rl(e),[{default:!0}]);var cu=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class lu{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return cu(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,i,n){return cu(this,void 0,void 0,function*(){const{getCardInstrument:r,getPaymentMethodOrThrow:o}=this._paymentIntegrationService.getState(),{payment:{methodId:a="",paymentData:s={}}={}}=t,d=gd(s)&&r(s.instrumentId),c=d?d.iin:n&&n.getBin();c&&(yield this._cardinalClient.runBinProcess(c));try{return yield e(q(t,{payment:{paymentData:{threeDSecure:{token:o(a).clientToken}}}}),i)}catch(e){if(!ca(e)||!Z(e.body.errors,{code:"three_d_secure_required"}))throw e;const i=yield this._cardinalClient.getThreeDSecureData(e.body.three_ds_result,this._getOrderData());if(!n)return void(yield this._paymentIntegrationService.submitPayment(q(t.payment,{paymentData:{threeDSecure:i}})));yield n.submit(q(t.payment,{paymentData:{threeDSecure:i}}))}})}_getClientToken(e){return cu(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(),i=e.getShippingAddress(),n=e.getCheckoutOrThrow(),r=e.getOrderOrThrow();return{billingAddress:t,shippingAddress:i,currencyCode:n.cart.currency.code,id:r.orderId.toString(),amount:n.cart.cartAmount}}}const uu=[100004,1010,1011,1020];var hu,pu,mu,yu,gu,vu,fu;!function(e){e.SetupCompleted="payments.setupComplete",e.Validated="payments.validated"}(hu||(hu={})),function(e){e.Init="init",e.Complete="complete",e.Confirm="confirm"}(pu||(pu={})),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"}(yu||(yu={})),function(e){e.BinProcess="bin.process"}(gu||(gu={})),function(e){e.CCA="cca"}(vu||(vu={})),function(e){e.Yes="Y",e.No="N"}(fu||(fu={}));class Su{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(V)}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((i,n)=>{t.on(hu.SetupCompleted,()=>{t.off(hu.SetupCompleted),t.off(hu.Validated),this._configurationToken=e,i()}),t.on(hu.Validated,e=>{t.off(hu.SetupCompleted),t.off(hu.Validated),e.ActionCode===mu.Error&&(P(uu,e.ErrorNumber)&&n(new Qi(Zi.MissingPaymentMethod)),n(new Kr(e.ErrorDescription)))}),t.setup(pu.Init,{jwt:e})}))}runBinProcess(e){return this._getClientSDK().then(t=>t.trigger(gu.BinProcess,e).catch(V)).then(e=>{if(!e||!e.Status)throw new nn(Xi.PaymentNotInitialized)})}getThreeDSecureData(e,t){return this._getClientSDK().then(i=>new Promise((n,r)=>{i.on(hu.Validated,(e,t)=>{if(i.off(hu.Validated),!t)return r(new Kr(e.ErrorDescription?e.ErrorDescription:"An error was encountered while processing the transaction."));if(!e.ActionCode)return n({token:t});switch(e.ActionCode){case mu.Success:return n({token:t});case mu.NoAction:return e.ErrorNumber>0?r(new Kr(e.ErrorDescription)):e.Payment&&e.Payment.ExtendedData&&e.Payment.ExtendedData.SignatureVerification===fu.Yes?n({token:t}):r(new Kr("Transaction signature could not be validated."));case mu.Failure:return r(new Kr("User failed authentication or an error was encountered while processing the transaction."));case mu.Error:return r(new Kr(e.ErrorDescription))}});const o={AcsUrl:e.acs_url,Payload:e.merchant_data},a=this._mapToPartialOrder(t,e.payer_auth_request);i.continue(vu.CCA,o,a)}))}_mapToPartialOrder(e,t){const i={BillingAddress:this._mapToCardinalAddress(e.billingAddress)};return e.paymentData&&(i.Account=this._mapToCardinalAccount(e.paymentData)),e.billingAddress.email&&(i.Email1=e.billingAddress.email),e.shippingAddress&&(i.ShippingAddress=this._mapToCardinalAddress(e.shippingAddress)),{Consumer:i,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 nn(Xi.PaymentNotInitialized);return this._sdk}}class wu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t){const i=t?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js";return this._scriptLoader.loadScript(`${i}?v=${e}`).then(()=>{if(!this._window.Cardinal)throw new pn;return this._window.Cardinal})}}var Iu=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class _u extends Rl{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Iu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:i}=this._paymentIntegrationService.getState(),n=i(e.methodId);n.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(n))})}execute(e,t){const i=Object.create(null,{execute:{get:()=>super.execute}});return Iu(this,void 0,void 0,function*(){const{payment:{methodId:n=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(n).config.is3dsEnabled?this._threeDSecureFlow.start(i.execute.bind(this),e,t,this._hostedForm):i.execute.call(this,e,t)})}}const Cu=Rt(e=>new _u(e,new lu(e,new Su(new wu(a())))),[{id:"cybersource"}]);var bu=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Pu{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return bu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode)})}start(e,t,i,n){var r,o,a,s;return bu(this,void 0,void 0,function*(){const{getCardInstrument:d}=this._paymentIntegrationService.getState(),{payment:c={methodId:""}}=t,{paymentData:l={}}=c;try{return yield e(t,i)}catch(e){if(ca(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,i=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,n);r&&(yield this._cardinalClient.runBinProcess(r));try{return yield this._submitPayment(c,{xid:i},n)}catch(e){if(ca(e)&&Z(e.body.errors,{code:"three_d_secure_required"})){const t=e.body.three_ds_result,i=null==t?void 0:t.payer_auth_request;return yield this._cardinalClient.getThreeDSecureData(t,this._getOrderData()),this._submitPayment(c,{token:i},n)}throw e}}throw e}})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),i=e.getShippingAddress(),{cart:{currency:{code:n},cartAmount:r}}=e.getCheckoutOrThrow();return{billingAddress:t,shippingAddress:i,currencyCode:n,id:e.getOrderOrThrow().orderId.toString(),amount:r}}_submitPayment(e,t,i){return bu(this,void 0,void 0,function*(){const n=q({},e,{paymentData:{threeDSecure:t}});i||(yield this._paymentIntegrationService.submitPayment(n)),yield null==i?void 0:i.submit(n)})}_getBin(e,t,i){const n=gd(e)&&t(e.instrumentId),r=function(e){const t=e;return!gd(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=i?i.getBin():r;return(n?n.iin:o)||""}}var Ou=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Eu extends Rl{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Ou(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:i}=this._paymentIntegrationService.getState(),n=i(e.methodId);n.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(n))})}execute(e,t){const i=Object.create(null,{execute:{get:()=>super.execute}});return Ou(this,void 0,void 0,function*(){const{payment:{methodId:n=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(n).config.is3dsEnabled?this._threeDSecureFlow.start(i.execute.bind(this),e,t,this._hostedForm):i.execute.call(this,e,t)})}}const Au=Rt(e=>new Eu(e,new Pu(e,new Su(new wu(a())))),[{id:"cybersourcev2"},{id:"bnz"}]);class Tu{constructor(e,t){this._formPoster=e,this._paymentIntegrationService=t}execute(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=i&&i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:r}))}catch(e){if(!ca(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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}redirectUrl(e){return this._formPoster.postForm(e,{})}_isAdditionalActionRequired(e){const{additional_action_required:t,status:i}=e;return"additional_action_required"===i&&t&&"offsite_redirect"===t.type}}const ku=Rt(e=>new Tu(Ee(),e),[{id:"laybuy"}]);function Du(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 Mu=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class zu extends Jo{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,i){const n=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Mu(this,void 0,void 0,function*(){yield n.initialize.call(this,e,t,i);const r=n.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new Qi(Zi.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 Mu(this,void 0,void 0,function*(){const i=yield t.getNonce.call(this,e),n=t.getPaymentMethod.call(this);return JSON.stringify({type:n.method,googlePayToken:i,browser_info:Xa()})})}processAdditionalAction(e){return Mu(this,void 0,void 0,function*(){if(!ca(e)||!Du(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,i)=>{const n=JSON.parse(e.action);this._getAdyenClient().createFromAction(n,{onAdditionalDetails:e=>{const i={methodId:n.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(i)},size:"05",onError:e=>i(e)}).mount("body"),i(new Vn)})}_getAdyenClient(){if(!this._adyenClient)throw new nn(Xi.PaymentNotInitialized);return this._adyenClient}}var Nu=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class xu{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t,this._isDeinitializationBlocked=!1,this._loadingIndicator=new td({containerStyles:Qs})}initialize(e){var t;return Nu(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!Xo(e.methodId))throw new gn('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 gn("Unable to proceed without valid options.");const{walletButton:n,loadingContainerId:r}=i,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(i,["walletButton","loadingContainerId"]);this._loadingIndicatorContainer=r,yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());const a=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(this._getMethodId());yield this._googlePayPaymentProcessor.initialize(()=>a,this._getGooglePayClientOptions(null===(t=a.initializationData)||void 0===t?void 0:t.storeCountry)),this._addPaymentButton(n,o)})}execute({payment:e}){return Nu(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new oo(["payment"]);yield this._paymentIntegrationService.submitOrder();const t=yield this._googlePayPaymentProcessor.getNonce(e.methodId),i=yield this._googlePayPaymentProcessor.extraPaymentData();try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign({nonce:t},i)}))}catch(t){yield this._googlePayPaymentProcessor.processAdditionalAction(t,e.methodId)}})}finalize(){return Promise.reject(new vd)}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 i=document.getElementById(e);if(!i)throw new gn("Unable to proceed without a walletButton.");this._paymentButton=i,this._clickListener=this._handleClick(t),this._paymentButton.addEventListener("click",this._clickListener)}_handleClick({onPaymentSelect:e,onError:t}){return i=>Nu(this,void 0,void 0,function*(){i.preventDefault();try{this._googlePayPaymentProcessor.setShouldRequestShipping(!1),yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(e){let i=e;if(this._toggleLoadingIndicator(!1),Zo(e)){if("CANCELED"===e.statusCode)throw new Vn;i=new Kr(JSON.stringify(e))}throw null==t||t(new Kr("An error occurred while requesting your Google Pay payment details.")),i}finally{this._toggleBlockDeinitialization(!1)}null==e||e()})}_interactWithPaymentSheet(){return Nu(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet();this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const t=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);t&&(yield this._paymentIntegrationService.updateBillingAddress(t)),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 tn(this._methodId,()=>new nn(Xi.PaymentNotInitialized))}_getIsSignedInOrThrow(){return Nu(this,void 0,void 0,function*(){try{return!!(yield this._googlePayPaymentProcessor.getNonce(this._getMethodId()))}catch(e){if(e instanceof Qi&&e.subtype===Zi.MissingPaymentToken)return!1;throw e}})}_handleOfferTrigger(e){return Nu(this,void 0,void 0,function*(){let t=!1,i="Sign in to Google Pay first to apply or remove promo codes.";try{t=yield this._getIsSignedInOrThrow()}catch(e){e instanceof Qi&&(i=e.message)}if(t){const{newOfferInfo:t,error:i}=yield this._googlePayPaymentProcessor.handleCoupons(e);return{newOfferInfo:t,error:i}}return{error:{reason:Ho.OFFER_INVALID,message:i,intent:$o.OFFER}}})}_getGooglePayClientOptions(e){return{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,offerData:i})=>Nu(this,void 0,void 0,function*(){if(t!==$o.INITIALIZE&&t!==$o.OFFER)return;const{offerChangeTriggers:n}=this._googlePayPaymentProcessor.getCallbackTriggers(),{newOfferInfo:r,error:o}=n.includes(t)?yield this._handleOfferTrigger(i):{},a=o;yield this._paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:s,getCartOrThrow:d}=this._paymentIntegrationService.getState(),{code:c,decimalPlaces:l}=d().currency,u=J(s().outstandingBalance,l).toFixed(l);return Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:c,totalPriceStatus:qo.FINAL,totalPrice:u})},r&&{newOfferInfo:r}),a&&{error:a})})}}}_toggleBlockDeinitialization(e){this._isDeinitializationBlocked=e}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this._loadingIndicator.show(this._loadingIndicatorContainer):this._loadingIndicator.hide()}}const Fu=Rt(e=>new xu(e,new ia(ra(),new zu(e,new md(a(),s())),i(),Ee())),[{id:"googlepayadyenv2"}]);var Ru=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Lu extends Jo{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,i){const n=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Ru(this,void 0,void 0,function*(){yield n.initialize.call(this,e,t,i);const r=n.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new Qi(Zi.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}processAdditionalAction(e){return Ru(this,void 0,void 0,function*(){if(!ca(e)||!Du(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 Ru(this,void 0,void 0,function*(){const i=yield t.getNonce.call(this,e),n=t.getPaymentMethod.call(this);return JSON.stringify({type:n.method,googlePayToken:i,browser_info:Xa()})})}_handleAction(e){return new Promise((t,i)=>{const n=JSON.parse(e.action);this._getAdyenClient().createFromAction(n,{onAdditionalDetails:e=>{const i={methodId:n.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(i)},size:"05",onError:e=>i(e)}).mount("body"),i(new Vn)})}_getAdyenClient(){if(!this._adyenClient)throw new nn(Xi.PaymentNotInitialized);return this._adyenClient}}const Bu=Rt(e=>new xu(e,new ia(ra(),new Lu(e,new Id(a(),s())),i(),Ee())),[{id:"googlepayadyenv3"}]),ju=Rt(e=>new xu(e,new ia(ra(),new sa(e),i(),Ee())),[{id:"googlepayauthorizenet"}]),Uu=Rt(e=>{const t=i();return new xu(e,new ia(ra(),new ha(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),qu=Rt(e=>new xu(e,new ia(ra(),new ma(e),i(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),Vu=Rt(e=>new xu(e,new ia(ra(),new va(e),i(),Ee())),[{id:"googlepayorbital"}]),Gu=Rt(e=>new xu(e,new ia(ra(),new xa(e,new ka(a())),i(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),Hu=Rt(e=>new xu(e,new ia(ra(),new La(e),i(),Ee())),[{id:"googlepayworldpayaccess"}]),$u=Rt(e=>{const t=i(),n=window,r=new bn(e),o=new Ln(new qn(a(),n,r));return new xu(e,new ia(ra(),new Ua(e,o),t,Ee()))},[{id:"googlepaybraintree"}]);var Wu,Yu;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(Wu||(Wu={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Yu||(Yu={}));var Ku=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ju extends xu{constructor(e,t,i,n){super(e,t),this._payPalCommerceSdk=i,this._requestSender=n}execute({payment:e}){return Ku(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new oo(["payment"]);const t=this._paymentIntegrationService.getState(),i=t.getCartOrThrow().id,{initializationData:n}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(i),{card_information:o}=n||{},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 Ku(this,void 0,void 0,function*(){const i=this._paymentIntegrationService.getState(),n=i.getPaymentMethodOrThrow(this._getMethodId());if(!n.initializationData)throw new Qi(Zi.MissingPaymentMethod);const r=i.getCartOrThrow().currency.code,o=yield this._payPalCommerceSdk.getPayPalGooglePaySdk(n,r,!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===Wu.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==Wu.Approved)throw new gn("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return Ku(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:i}=yield this._requestSender.post("/api/storefront/payments/googlepaypaypalcommercecheckout",{headers:Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr),body:t});return i})}}const Zu=Rt(e=>{const t=new Ga(a());return new Ju(e,new ia(ra(),new Wa(e,t),i(),Ee()),t,i())},[{id:"googlepaypaypalcommerce"}]);var Xu,Qu;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(Xu||(Xu={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Qu||(Qu={}));var eh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class th extends xu{constructor(e,t,i,n){super(e,t),this._payPalSdkHelper=i,this._requestSender=n}execute({payment:e}){return eh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new oo(["payment"]);const t=this._paymentIntegrationService.getState(),i=t.getCartOrThrow().id,{initializationData:n}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(i),{card_information:o}=n||{},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 eh(this,void 0,void 0,function*(){const i=this._paymentIntegrationService.getState(),n=i.getPaymentMethodOrThrow(this._getMethodId());if(!n.initializationData)throw new Qi(Zi.MissingPaymentMethod);const r=i.getCartOrThrow().currency.code,o=yield this._payPalSdkHelper.getPayPalGooglePaySdk(n,r,!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===Xu.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==Xu.Approved)throw new gn("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return eh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:i}=yield this._requestSender.post("/api/storefront/payments/googlepay_bigcommerce_paymentscheckout",{headers:Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr),body:t});return i})}}const ih=Rt(e=>{const t=new Mr(a());return new th(e,new ia(ra(),new Ja(e,t),i(),Ee()),t,i())},[{id:"googlepay_bigcommerce_payments"}]),nh=Rt(e=>new xu(e,new ia(ra(),new es(e,Ee()),i(),Ee())),[{id:"googlepaytdonlinemart"}]);class rh extends Ji{constructor(e,t,i){super(i||"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 oh{constructor(e,t){this.paymentIntegrationService=e,this.formPoster=t}execute(e,t){var i,n,r,o,a;return n=this,r=void 0,a=function*(){const{payment:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!(null==n?void 0:n.methodId))throw new oo(["payment.methodId"]);yield this.paymentIntegrationService.loadPaymentMethod(n.methodId,t);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n.methodId);if(!(null===(i=o.initializationData)||void 0===i?void 0:i.processable))throw new rh("payment.humm_not_processable_error","hummNotProcessableError");yield this.paymentIntegrationService.submitOrder(r,t);try{yield this.paymentIntegrationService.submitPayment({methodId:n.methodId})}catch(e){return this.isOffsiteRedirectResponse(e)?this.handleOffsiteRedirectResponse(e):Promise.reject(e)}},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())})}finalize(){return Promise.reject(new vd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}handleOffsiteRedirectResponse(e){const t=e.body.additional_action_required.data.redirect_url,i=e.body.provider_data;return new Promise(e=>{this.formPoster.postForm(t,JSON.parse(i),e)})}isOffsiteRedirectResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!t.body)return!1;const i=t.body;return"additional_action_required"===i.status&&!!i.additional_action_required&&"offsite_redirect"===i.additional_action_required.type&&"string"==typeof i.provider_data}}const ah=Rt(e=>new oh(e,Ee()),[{id:"humm"}]),sh=["AT","BE","CA","CH","CZ","DE","DK","ES","FI","FR","GB","GR","IE","IT","NL","NO","NZ","PL","PT","SE"],dh=["AU"];var ch=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class lh{constructor(e,t){this.paymentIntegrationService=e,this.klarnaScriptLoader=t}initialize(e){return ch(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 ch(this,void 0,void 0,function*(){if(!e.payment)throw new gn('Unable to proceed because "payload.payment" argument is not provided.');const i=e.payment,{paymentData:n}=i,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(i,["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 vd)}loadWidget(e){return ch(this,void 0,void 0,function*(){if(!e.klarna)throw new gn('Unable to load widget because "options.klarna" argument is not provided.');const{methodId:t,klarna:{container:i,onLoad:n}}=e;return yield this.paymentIntegrationService.loadPaymentMethod(t),new Promise(e=>{const r=this.paymentIntegrationService.getState().getPaymentMethod(t);if(!r)throw new Qi(Zi.MissingPaymentMethod);if(!this.klarnaCredit||!r.clientToken)throw new nn(Xi.PaymentNotInitialized);this.klarnaCredit.init({client_token:r.clientToken}),this.klarnaCredit.load({container:i},t=>{n&&n(t),e(t)})})})}getUpdateSessionData(e,t){if(!P([...sh,...dh],e.countryCode))return{};const i={billing_address:this.mapToKlarnaAddress(e,e.email)};return t&&(i.shipping_address=this.mapToKlarnaAddress(t,e.email)),i}needsStateCode(e){return P(dh,e)}mapToKlarnaAddress(e,t){const i={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&&(i.street_address2=e.address2),e.phone&&(i.phone=e.phone),i}authorize(){return new Promise((e,t)=>{const i=this.paymentIntegrationService.getState(),n=i.getBillingAddress(),r=i.getShippingAddress();if(!n)throw new Qi(Zi.MissingBillingAddress);if(!this.klarnaCredit)throw new nn(Xi.PaymentNotInitialized);const o=this.getUpdateSessionData(n,r);this.klarnaCredit.authorize(o,i=>i.approved?e(i):i.show_form?t(new Vn):void t(new Jr))})}}class uh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,i,n,r,o;return i=this,n=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 pn;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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())})}}const hh=Rt(e=>new lh(e,new uh(a())),[{id:"klarna"}]);var ph=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class mh{constructor(e,t,i){this.paymentIntegrationService=e,this.klarnav2ScriptLoader=t,this.klarnav2TokenUpdater=i}initialize(e){return ph(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 ph(this,void 0,void 0,function*(){if(!e.payment)throw new gn('Unable to proceed because "payload.payment" argument is not provided.');const i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e.payment,[]),{gatewayId:n,methodId:r}=i;if(!n)throw new gn('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,n,r),{authorization_token:u}=yield this.authorizeOrThrow(l,r);yield this.paymentIntegrationService.initializePayment(n,{authorizationToken:u}),yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:i,useStoreCredit:e.useStoreCredit}),t)})}finalize(){return Promise.reject(new vd)}loadPaymentsWidget(e){return ph(this,void 0,void 0,function*(){if(!e.klarnav2)throw new gn('Unable to load widget because "options.klarnav2" argument is not provided.');const{methodId:t,gatewayId:i,klarnav2:{container:n,onLoad:r}}=e;if(!i)throw new gn('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(i,{params:a}).catch(()=>{throw new Qi(Zi.MissingPaymentMethod)}),new Promise(e=>{const a=o.getPaymentMethodOrThrow(t),{klarnaMultipleRadioButton:s}=a.initializationData||{};if(!this.klarnaPayments||!a.clientToken)throw new nn(Xi.PaymentNotInitialized);this.klarnaPayments.init({client_token:a.clientToken}),this.klarnaPayments.load({container:n,payment_method_category:this.isKlarnaMultipleRadioButtonEnabled(s,i,t)},t=>{r&&r(t),e(t)})})})}getUpdateSessionData(e,t,i){if(!P([...sh,...dh],t.countryCode))return{};const n={billing_address:this.mapToKlarnaAddress(e,t,t.email)};return i&&(n.shipping_address=this.mapToKlarnaAddress(e,i,t.email)),n}needsStateCode(e){return P(dh,e)}isKlarnaMultipleRadioButtonEnabled(e,t,i){return e?i:t}mapToKlarnaAddress(e,t,i){const n=this.paymentIntegrationService.getState(),{checkoutSettings:r}=n.getStoreConfigOrThrow(),o=n.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:i};return t.address2&&(s.street_address2=t.address2),t.phone&&(s.phone=t.phone),t.company&&a&&Wt(r.features,"PI-3915.b2b_payment_session_for_klarna")&&(s.organization_name=t.company),s}authorizeOrThrow(e,t){return ph(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const i=this.paymentIntegrationService.getState(),n=i.getBillingAddressOrThrow(),r=i.getShippingAddress(),o=this.getUpdateSessionData(t,n,r);return new Promise((t,i)=>{if(!this.klarnaPayments)return i(new nn(Xi.PaymentNotInitialized));this.klarnaPayments.authorize({payment_method_category:e},o,e=>e.approved?t(e):e.show_form?i(new Vn):void i(new Jr))})})}}class yh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,i,n,r,o;return i=this,n=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 pn;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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())})}}class gh{constructor(e){this.requestSender=e}updateClientToken(e,{timeout:t,params:i}={}){const n=`/api/storefront/payments/${e}`;return this.requestSender.get(n,{timeout:t,headers:Object.assign({Accept:ur.JsonV1,"X-API-INTERNAL":cr},hr),params:i})}klarnaOrderInitialization(e,t){return i=this,n=void 0,o=function*(){const i={headers:Object.assign({Accept:ur.JsonV1,"X-API-INTERNAL":cr},hr),body:{cartId:e,clientToken:t}};yield this.requestSender.put("/api/storefront/initialization/klarna",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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}const vh=Rt(e=>{const{getHost:t}=e.getState(),n=i({host:t()});return new mh(e,new yh(a()),new gh(n))},[{gateway:"klarna"}]);class fh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return i=this,n=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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Sh=Rt(e=>new fh(e),[{id:"testgateway"}]);var wh,Ih=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e.CREDIT_CARD="credit_card"}(wh||(wh={}));const _h=["klarnapaylater","klarnasliceit"];class Ch{constructor(e,t){this.mollieScriptLoader=e,this.paymentIntegrationService=t}initialize(e){return Ih(this,void 0,void 0,function*(){const{mollie:t,methodId:i,gatewayId:n}=e;if(!t)throw new gn('Unable to initialize payment because "options.mollie" argument is not provided.');if(!i||!n)throw new gn('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.');const r=document.querySelectorAll(".mollie-components-controller");v(r,e=>e.remove());const o=this.paymentIntegrationService.getState(),a=o.getStoreConfigOrThrow();this.initializeOptions=t;const s=o.getPaymentMethodOrThrow(i,n),{config:{merchantId:d,testMode:c}}=s;if(this.locale=o.getLocale(),!d)throw new Qi(Zi.MissingPaymentMethod);return this.isCreditCard(i)&&t.form&&this.shouldShowTSVHostedForm(i,n)?this.hostedForm=yield this.mountCardVerificationfields(t.form):this.isCreditCard(i)&&(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(`${n}-${i}-paragraph`);e&&e.remove(),t.disableButton(!1),this.loadPaymentMethodsAllowed(t,i,n)}},this.unsubscribe(),this.loadPaymentMethodsAllowed(t,i,n),Promise.resolve()})}execute(e,t){return Ih(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=null==i?void 0:i.paymentData;if(!i||!i.gatewayId||!r)throw new oo(["payment","gatewayId","paymentData"]);try{return yield this.paymentIntegrationService.submitOrder(n,t),gd(r)?yield this.executeWithVaulted(i):this.isCreditCard(i.methodId)?yield this.executeWithCC(i):yield this.executeWithAPM(i)}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 Ih(this,void 0,void 0,function*(){const t=e.paymentData,{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:n=!1}=_d(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:i,set_as_default_stored_instrument:n,browser_info:Xa(),shopper_locale:this.getShopperLocale()};yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:a}}))})}executeWithVaulted(e){return Ih(this,void 0,void 0,function*(){if(this.isHostedPaymentFormEnabled(e.methodId,e.gatewayId)){const t=this.hostedForm;if(!t)throw new nn(Xi.PaymentNotInitialized);yield t.validate(),yield t.submit(e),yield this.paymentIntegrationService.loadCurrentOrder()}else yield this.paymentIntegrationService.submitPayment(e)})}executeWithAPM(e){return Ih(this,void 0,void 0,function*(){const t=e.paymentData,i=t&&"issuer"in t?t.issuer:"";yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign(Object.assign({},t),{formattedPayload:{issuer:i,shopper_locale:this.getShopperLocale()}})}))})}isCreditCard(e){return e===wh.CREDIT_CARD}shouldShowTSVHostedForm(e,t){return this.isHostedPaymentFormEnabled(e,t)&&this.isHostedFieldAvailable()}mountCardVerificationfields(e){return new Promise((t,i)=>Ih(this,void 0,void 0,function*(){try{const i=this.paymentIntegrationService.getState().getStoreConfig(),n=null==i?void 0:i.paymentSettings.bigpayBaseUrl;if(!n)throw new Qi(Zi.MissingCheckoutConfig);const r=this.paymentIntegrationService.createHostedForm(n,e);yield r.attach(),t(r)}catch(e){i(e)}}))}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:i}=this.paymentIntegrationService.getState();return!0===i(e,t).config.isHostedFormEnabled}isHostedFieldAvailable(){var e;return!!(null===(e=this.getInitializeOptions().form)||void 0===e?void 0:e.fields)}processAdditionalAction(e){if(!ca(e))return Promise.reject(e);if(Z(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 nn(Xi.PaymentNotInitialized);return this.initializeOptions}loadMollieJs(e,t,i=!1){return this.mollieClient?Promise.resolve(this.mollieClient):this.mollieScriptLoader.load(e,t,i)}getMollieClient(){if(!this.mollieClient)throw new nn(Xi.PaymentNotInitialized);return this.mollieClient}getShopperLocale(){if(!this.locale)throw new nn(Xi.PaymentNotInitialized);return this.locale}mountElements(){const{containerId:e,cardNumberId:t,cardCvcId:i,cardExpiryId:n,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(`#${i}`),this.expiryDateElement=e.createComponent("expiryDate",{styles:o}),this.expiryDateElement.mount(`#${n}`)}},0)}loadPaymentMethodsAllowed(e,t,i){var n;if(_h.includes(t)){const r=null===(n=this.paymentIntegrationService.getState().getCartOrThrow().lineItems)||void 0===n?void 0:n.digitalItems;if(r&&r.length>0){const{containerId:n}=this.getInitializeOptions();if(n){const r=document.getElementById(n);if(r){const n=document.createElement("p");n.setAttribute("id",`${i}-${t}-paragraph`),e.unsupportedMethodMessage&&(n.innerText=e.unsupportedMethodMessage,r.appendChild(n),e.disableButton(!0))}}}}}}class bh{constructor(e,t=window){this.scriptLoader=e,this.mollieHostWindow=t}load(e,t,i){return n=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 pn;return this.mollieHostWindow.Mollie(e,{locale:t,testmode:i})},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())});var n,r,o,a}}const Ph=Rt(e=>new Ch(new bh(a()),e),[{gateway:"mollie"},{gateway:"mollie",id:"applepay"}]);var Oh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};const Eh="moneris-payment-iframe";class Ah{constructor(e){this.paymentIntegrationService=e}initialize(e){return Oh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{moneris:i,methodId:n}=e;if(!n)throw new gn('Unable to initialize payment because "methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.moneris" argument is not provided.');this.initializeOptions=i;const{config:r,initializationData:o}=t.getPaymentMethodOrThrow(n);if(!(null==o?void 0:o.profileId))throw new Qi(Zi.MissingPaymentMethod);return i.form&&this.shouldShowTSVHostedForm(n)&&(this.hostedForm=yield this.mountCardVerificationfields(i.form)),this.iframe||(this.iframe=this.createIframe(i.containerId,o,!!r.testMode)),Promise.resolve()})}execute(e,t){return Oh(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{isStoreCreditApplied:r}=this.paymentIntegrationService.getState().getCheckoutOrThrow();if(r&&(yield this.paymentIntegrationService.applyStoreCredit(r)),yield this.paymentIntegrationService.submitOrder(n,t),!i.paymentData||!gd(i.paymentData))return this.executeWithCC(i);yield this.executeWithVaulted(i)})}finalize(){return Promise.reject(new vd)}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 Oh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId).config.testMode,i=e.paymentData||{},n=_d(i)?i:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o}=n,a=yield new Promise((e,i)=>{if(!this.iframe)throw new nn(Xi.PaymentNotInitialized);const n=this.iframe.contentWindow;if(null===n)throw new nn(Xi.PaymentNotInitialized);n.postMessage("tokenize",this.monerisURL(!!t)),this.windowEventListener=n=>{if("string"==typeof n.data&&n.origin===`https://${t?"esqa":"www3"}.moneris.com`)try{e(this.handleMonerisResponse(n))}catch(e){i(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 Oh(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(),i=H(null===(e=t.form)||void 0===e?void 0:e.fields,E);return!E(i)}getInitializeOptions(){if(!this.initializeOptions)throw new nn(Xi.PaymentNotInitialized);return this.initializeOptions}mountCardVerificationfields(e){var t;return Oh(this,void 0,void 0,function*(){const i=null===(t=this.paymentIntegrationService.getState().getStoreConfig())||void 0===t?void 0:t.paymentSettings.bigpayBaseUrl;if(!i)throw new Qi(Zi.MissingCheckoutConfig);const n=this.paymentIntegrationService.createHostedForm(i,e);return yield n.attach(),n})}createIframe(e,t,i,n){const r=document.getElementById(e);if(!r)throw new gn("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==n?void 0:n.cssBody)||"font-family: Arial, Helvetica,sans-serif;background: transparent;",css_textbox:(null==n?void 0:n.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==n?void 0:n.cssTextboxCardNumber)||"width: 240px;",css_textbox_exp:(null==n?void 0:n.cssTextboxExpiryDate)||"margin-bottom: 0;width: calc(30% - 12px);",css_textbox_cvd:(null==n?void 0:n.cssTextboxCVV)||"margin-bottom: 0;width: calc(30% - 12px);",css_input_label:(null==n?void 0:n.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=B(a,(e,t)=>`${t}=${e}`).join("&");return o.width="100%",o.height="100%",o.name=Eh,o.id=Eh,o.style.border="none",o.src=`${this.monerisURL(i)}?${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 Th=Rt(e=>new Ah(e),[{id:"moneris"}]);class kh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return i=this,n=void 0,o=function*(){yield this._paymentIntegrationService.submitOrder(G(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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Dh=Rt(e=>new kh(e),[{id:"nopaymentdatarequired"}]);class Mh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return i=this,n=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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const zh=Rt(e=>new Mh(e),[{type:"PAYMENT_TYPE_OFFLINE"}]);var Nh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class xh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return Nh(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=this._shouldSubmitFullPayload(i)?e:n,o=i&&i.paymentData,a=o&&gd(o)&&o.instrumentId||void 0,s=o&&_d(o)&&o.shouldSaveInstrument||void 0,d=o&&_d(o)&&o.shouldSetAsDefaultInstrument||void 0;if(!i)throw new oo(["payment"]);const{methodId:c,gatewayId:l}=i;yield this._paymentIntegrationService.submitOrder(r,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:c,gatewayId:l,instrumentId:a,shouldSaveInstrument:s,shouldSetAsDefaultInstrument:d})})}finalize(e){return Nh(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),i=t.getOrder(),n=t.getPaymentStatus();if(!i||n!==Gc.ACKNOWLEDGE&&n!==Gc.FINALIZE)return Promise.reject(new vd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_shouldSubmitFullPayload(e){return!!e&&("adyen"===e.gatewayId||"barclaycard"===e.gatewayId)}}const Fh=Rt(e=>new xh(e),[{type:"PAYMENT_TYPE_HOSTED"}]),Rh={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},Lh=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 Bh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class jh{constructor(e,t,i,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalCommerceSdk=i,this.loadingIndicator=n}initialize(e){var t;return Bh(this,void 0,void 0,function*(){const{methodId:i,paypalcommerce:n}=e||{};if(this.paypalcommerce=n,!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(i),{container:a,bannerContainerId:s}=n,{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.paypalCommerceSdk.getPayPalMessages(o,r.getCartOrThrow().currency.code);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.paypalCommerceIntegrationService.loadPayPalSdk(i),n.onInit&&"function"==typeof n.onInit&&n.onInit(()=>this.renderButton(i,n)),(void 0===n.shouldRenderPayPalButtonOnInitialization||n.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(i,n))})}execute(e,t){var i,n;return Bh(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{onError:a}=this.paypalcommerce||{};if(!r)throw new oo(["payment"]);const{methodId:s,paymentData:d}=r;if(this.isPayPalVaultedInstrumentPaymentData(d)&&!this.orderId&&(this.orderId=yield this.createOrder()),!this.orderId)throw new Jr;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 ca(e)&&"offsite_redirect"===(null===(t=e.body.additional_action_required)||void 0===t?void 0:t.type)}(e)){const t=null===(n=null===(i=e.body.additional_action_required)||void 0===i?void 0:i.data)||void 0===n?void 0:n.redirect_url;return new Promise(()=>window.location.replace(t))}return this.isProviderError(e)&&(yield this.paypalCommerceIntegrationService.loadPayPalSdk(r.methodId),yield new Promise((e,t)=>{var i;this.paypalcommerce&&(null===(i=this.paypalButton)||void 0===i||i.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 vd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,i){const{instrumentId:n,shouldSetAsDefaultInstrument:r}=i,o=!this.isTrustedVaultingFlow(i);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:n,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:n}}}}}preparePaymentPayload(e,t,i){const{shouldSaveInstrument:n=!1,shouldSetAsDefaultInstrument:r=!1}=_d(i)?i:{};return{methodId:e,paymentData:{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var i,n,r,o;const a=this.paypalCommerceIntegrationService.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 gn('Unable to initialize payment because "container" argument is not provided.');const y=Object.assign(Object.assign({},this.isPaypalCommerceAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.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===(n=(i=this.paypalButton).hasReturned)||void 0===n?void 0:n.call(i))&&this.isPaypalCommerceAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return Bh(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;return null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return Bh(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.paypalCommerceIntegrationService.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&&gd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),i=null==t?void 0:t.find(t=>Wd(t)&&t.bigpayToken===e.instrumentId);return!(Wd(i)&&!i.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&gd(e)&&_d(e)}renderMessages(e,t,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Lh(i)};e.Messages(n).render(`#${t}`)}isProviderError(e){var t,i,n;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(n=null===(i=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===i?void 0:i.provider_error)||void 0===n?void 0:n.code)}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}}const Uh=Rt(e=>new jh(e,ys(e),new Ga(a()),new td({containerStyles:Rh})),[{id:"paypalcommerce"}]);function qh(){return new Ga(o())}var Vh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Gh{constructor(e,t,i,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=i,this.paypalCommerceSdk=n}initialize(e){return Vh(this,void 0,void 0,function*(){const{methodId:t,paypalcommerce:i,paypalcommercecredit:n}=e||{},r=n||i;if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new gn('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.paypalCommerceSdk.getPayPalMessages(a,o.getCartOrThrow().currency.code);return this.renderMessages(t,c,e)}d?this.orderId=d:(yield this.paypalCommerceIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==l?void 0:l.split("#")[1],this.renderButton(t,r))})}execute(e,t){return Vh(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);if(!this.orderId)throw new Jr;yield this.paymentIntegrationService.submitOrder(n,t),yield this.paypalCommerceIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new vd)}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 gn('Unable to initialize payment because "container" argument is not provided.');const i=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=n.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u=[i.FUNDING.PAYLATER,i.FUNDING.CREDIT];let h=!1;u.forEach(e=>{if(h)return;const t={fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o),createOrder:()=>this.paypalCommerceIntegrationService.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=i.Buttons(t),this.paypalButton.isEligible()||e!==i.FUNDING.PAYLATER){if(!this.paypalButton.isEligible()&&e===i.FUNDING.CREDIT)throw new vn(`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 Vh(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;if(t&&"function"==typeof t)return t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}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,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Lh(i)};e.Messages(n).render(`#${t}`)}}const Hh=Rt(e=>new Gh(e,ys(e),new td({containerStyles:Rh}),qh()),[{id:"paypalcommercecredit"}]);var $h=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Wh{constructor(e,t,i){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=i}initialize(e){var t,i;return $h(this,void 0,void 0,function*(){const{methodId:n,paypalcommerce:r,paypalcommercevenmo:o}=e||{},a=o||r;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!a)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);(null===(t=s.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(i=s.initializationData)||void 0===i?void 0:i.orderId:(yield this.paypalCommerceIntegrationService.loadPayPalSdk(n),this.loadingIndicatorContainer=a.container.split("#")[1],this.renderButton(n,a))})}execute(e,t){return $h(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);if(!this.orderId)throw new Jr;yield this.paymentIntegrationService.submitOrder(n,t),yield this.paypalCommerceIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){const i=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=n.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u={fundingSource:i.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=i.Buttons(u),!this.paypalButton.isEligible())throw new vn("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 $h(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;return t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}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 Yh=Rt(e=>new Wh(e,ys(e),new td({styles:{backgroundColor:"black"}})),[{id:"paypalcommercevenmo"}]);var Kh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Jh{constructor(e,t,i,n){this.formPoster=e,this.paymentIntegrationService=t,this.paypalRequestSender=i,this.paypalSdkLoader=n}loadPayPalSdk(e,t,i,n){return Kh(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.paypalSdkLoader.getPayPalSDK(a,o,i,n),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new pn;return this.paypalSdk}createBuyNowCartOrThrow(e){return Kh(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new Zn}})}createOrder(e,t){return Kh(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:i},t));return n})}createOrderCardFields(e,t){return Kh(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n,setupToken:r}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:i},t));return Object.assign({orderId:n},r?{setupToken:r}:{})})}updateOrder(e){return Kh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getConsignmentsOrThrow()[0];try{yield this.paypalRequestSender.updateOrder(e,{availableShippingOptions:n.availableShippingOptions,cartId:i.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new Qn}})}getOrderStatus(e,t){return Kh(this,void 0,void 0,function*(){try{const{status:i}=yield this.paypalRequestSender.getOrderStatus(e,t);return i}catch(e){throw new Qn}})}tokenizePayment(e,t){const i=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new Qi(Zi.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},i.source===kt.BuyNow&&{cart_id:i.id}))}submitPayment(e,t,i){return Kh(this,void 0,void 0,function*(){const n={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:n},i?{gatewayId:i}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],i=t.availableShippingOptions||[],n=i.find(e=>e.isRecommended),r=(e?i.find(t=>t.id===e):i.find(e=>{if(t.selectedShippingOption){const i=t.selectedShippingOption.id;return e.id===i}return!1}))||n||i[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,i;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===(i=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===i?void 0:i.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:i}=e,{address:n,name:{full_name:r}}=i[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:n.address_line_1,address2:n.address_line_2,city:n.admin_area_2,countryCode:n.country_code,postalCode:n.postal_code,stateOrProvinceCode:n.admin_area_1})}getValidButtonStyle(e={}){const{color:t,height:i,label:n,shape:r}=e,o={color:t&&ks[t]?t:void 0,height:this.getValidHeight(i),label:n&&Ts[n]?n:void 0,shape:r&&Ds[r]?r:void 0};return H(o,k)}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 Zh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Xh{constructor(e){this.requestSender=e}createOrder(e,t){return Zh(this,void 0,void 0,function*(){const i=`/api/storefront/payment/${e}`,n=t,r=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.post(i,{headers:r,body:n})).body})}updateOrder(e,t){return Zh(this,void 0,void 0,function*(){const i=`/api/storefront/initialization/${e}`,n=t,r=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.put(i,{headers:r,body:n})).body})}getOrderStatus(e,t){return Zh(this,void 0,void 0,function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body})}}const Qh=e=>{const{getHost:t}=e.getState();return new Jh(Ee(),e,new Xh(i({host:t()})),Rs())};var ep=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class tp{constructor(e,t,i,n,r=3e3,o=3e5){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalSdkScriptLoader=i,this.loadingIndicator=n,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=V,this.isPollingEnabled=!1}initialize(e){return ep(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,paypalcommerce:n,paypalcommercealternativemethods:r}=e,o=r||n;if(this.paypalcommercealternativemethods=r,!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!o)throw new gn('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');const a=this.paymentIntegrationService.getState(),s=a.getPaymentMethodOrThrow(i,t),{orderId:d,shouldRenderFields:c}=s.initializationData||{},l=a.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=Wt(l,"PAYPAL-5192.paypal_commerce_ideal_polling"),d?this.orderId=d:(this.paypalApms=yield this.paypalSdkScriptLoader.getPayPalApmsSdk(s,a.getCartOrThrow().currency.code),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(i,t,o),c&&this.renderFields(i,o))})}execute(e,t){return ep(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{methodId:r,gatewayId:o}=i;if(!this.orderId)throw new Jr;this.isPollingEnabled&&"ideal"===r&&(yield new Promise((e,t)=>{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)||(yield this.paymentIntegrationService.submitOrder(n,t)),yield this.paypalCommerceIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;return this.orderId=void 0,this.isPollingEnabled&&this.resetPollingMechanism(),null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,i,n){return ep(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceIntegrationService.getOrderStatus(null!=n?n:"paypalcommerce"),o=r===ds.Approved,a=r===ds.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return i();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,paypalcommercealternativemethods:this.paypalcommercealternativemethods}),this.handleError(new rc)}catch(e){i()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}reinitializeStrategy(e){return ep(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}handleError(e){const{onError:t}=this.paypalcommercealternativemethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderButton(e,t,i){const n=this.getPaypalAmpsSdkOrThrow(),r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t),{buttonStyle:o}=r.initializationData||{},{container:a,onError:s,onRenderButton:d,submitForm:c}=i,l={fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o),onInit:(e,t)=>i.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,i),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deinitializePollingMechanism()},onError:e=>{this.deinitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>ep(this,void 0,void 0,function*(){return i.onValidate(t.resolve,t.reject)})};this.paypalButton=n.Buttons(l),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}onCreateOrder(e,t,i){return ep(this,void 0,void 0,function*(){const{onValidate:n}=i;yield n(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),V);const r=yield this.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethodscheckout");if(this.isNonInstantPaymentMethod(e)){const i={useStoreCredit:!1},n={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(i,n),yield this.paypalCommerceIntegrationService.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 i=this.getPaypalAmpsSdkOrThrow(),n=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=n.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new gn('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}}};i.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in ss}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new pn;return this.paypalApms}}const ip=Rt(e=>new tp(e,Qh(e),Rs(),new td({containerStyles:Rh})),[{gateway:"paypalcommercealternativemethods"}]);var np=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class rp{constructor(e,t,i,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalSdkScriptLoader=i,this.paypalFastlaneUtils=n}initialize(e){return np(this,void 0,void 0,function*(){const{methodId:t,paypalcommercecreditcards:i,paypalcommerce:n}=e,r=i||n,{form:o,onCreditCardFieldsRenderingError:a,onLoadComplete:s}=r||{};if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new gn('Unable to proceed because "options.paypalcommercecreditcards.form" argument is not provided.');this.hostedFormOptions=o,this.isCreditCardForm=lc(o.fields),this.isCreditCardVaultedForm=uc(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 np(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{methodId:r,paymentData:o}=i||{};if(!i||!r)throw new oo(["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(n,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e,t,i,n;return np(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===(i=this.numberField)||void 0===i?void 0:i.close(),yield null===(n=this.nameField)||void 0===n?void 0:n.close(),Promise.resolve()})}preparePaymentPayload(e,t,i,n){const{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=_d(t)?t:{},a=t&&gd(t)?t.instrumentId:void 0,s=H({verification_nonce:n,token:a},k);return{methodId:e,paymentData:{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o,instrumentId:a,formattedPayload:Object.assign(Object.assign({},n||a?{bigpay_token:s}:{}),i?{card_with_order:{order_id:i}}:{})}}}initializeFields(e,t){return np(this,void 0,void 0,function*(){const{fields:i,styles:n}=e,r=this.paypalIntegrationService.getPayPalSdkOrThrow(),o=this.getExecuteCallback(i),a=Object.assign({style:this.getInputStyles(n),onApprove:({orderID:e,vaultSetupToken:t,liabilityShift:i})=>{if(i===is.No||i===is.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Kr},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 nn(Xi.PaymentNotInitialized);try{this.stylizeInputContainers(i),lc(i)&&(yield this.renderFields(i)),uc(i)&&(yield this.renderVaultedFields(i))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return uc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>np(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:()=>np(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,i,n,r;return np(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===(i=e.cardExpiry)||void 0===i?void 0:i.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(n=e.cardName)||void 0===n?void 0:n.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,i,n;return np(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===(i=e.cardExpiryVerification)||void 0===i?void 0:i.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(n=e.cardNumberVerification)||void 0===n?void 0:n.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(_d(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(gd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return np(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i={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(i)}catch(e){throw new Kr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return np(this,void 0,void 0,function*(){const i=this.getCardFieldsOrThrow(),n=yield i.getState().then(e=>e),r=this.getValidityData(n);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 ao(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const i=Object.keys(t);return{isValid:i.every(e=>{var i;return null===(i=t[e])||void 0===i?void 0:i.isValid}),errors:i.reduce((e,i)=>{var n;const r=this.mapFieldType(i);return Object.assign(Object.assign({},e),{[r]:(null===(n=t[i])||void 0===n?void 0:n.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case cc.CardCode:case cc.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case cc.CardNumber:case cc.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case cc.CardExpiry:case cc.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(i=>{var n,r;t[i]=[{message:(null===(r=null===(n=e[i])||void 0===n?void 0:n[0])||void 0===r?void 0:r.message)||"",type:i}]}),t}mapFieldType(e){switch(e){case"name":return cc.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?cc.CardNumber:cc.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?cc.CardExpiry:cc.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?cc.CardCode:cc.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new nn(Xi.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,i,n;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.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 i;null===(i=null==e?void 0:e.onValidate)||void 0===i||i.call(e,this.getValidityData(t))}onFocusHandler(e,t){var i;null===(i=null==e?void 0:e.onFocus)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var i;null===(i=null==e?void 0:e.onBlur)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var i;null===(i=null==e?void 0:e.onEnter)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,i;const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(e),o=n.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===(i=null==r?void 0:r.initializationData)||void 0===i?void 0:i.isPayPalCommerceAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return np(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getPaymentMethodOrThrow(e),{initializationData:r}=n;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(n,i.currency.code,i.id);yield this.paypalFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const op=Rt(e=>new rp(e,Qh(e),Rs(),js()),[{id:"paypalcommercecreditcards"}]);var ap=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class sp{constructor(e,t,i,n=3e3,r=3e5){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=i,this.pollingInterval=n,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=V}initialize(e){return ap(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,paypalcommerceratepay:n}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.paypalcommerceratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=n;if(!o)throw new gn('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new gn('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,t),{merchantId:d}=s.initializationData||{};if(!d)throw new gn("Unable to initialize payment because merchantId argument is not provided.");this.paypalcommerceratepay=n,yield this.paypalCommerceIntegrationService.loadPayPalSdk(i),this.createFraudNetScript(d,i,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return ap(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{getFieldsValues:r}=this.paypalcommerceratepay||{};if(!i)throw new oo(["payment"]);if(!r||"function"!=typeof r)throw new gn('Unable to initialize payment because "options.getFieldsValues" argument is not provided.');this.toggleLoadingIndicator(!0);try{const e=yield this.paypalCommerceIntegrationService.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:i.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(n,t),yield this.paymentIntegrationService.submitPayment({methodId:i.methodId,paymentData:d}),yield new Promise((e,t)=>{this.initializePollingMechanism(i.methodId,e,t,i.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new vd)}deinitialize(){const{legalTextContainer:e}=this.paypalcommerceratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],i=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),i.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),i=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${i}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const i=e,n=t.split("#")[1],r=document.getElementById(n),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",i),null==o||o.prepend(a);const s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(i))throw new gn('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${i}`)}handleError(e){const{onError:t}=this.paypalcommerceratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,i){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,i),{testMode:r}=n.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 ap(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,i,n){return ap(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceIntegrationService.getOrderStatus("paypalcommercealternativemethods",{params:{useMetadata:!0}}),o=r===ds.PollingStop,a=r===ds.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return i();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,paypalcommerceratepay:this.paypalcommerceratepay}),this.handleError(new rc)}catch(e){this.handleError(e),i()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const dp=Rt(e=>new sp(e,ys(e),new td({containerStyles:Object.assign(Object.assign({},Rh),{position:"fixed"})})),[{gateway:"paypalcommercealternativemethods",id:"ratepay"}]);function cp(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var lp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class up{constructor(e,t,i,n){this.paymentIntegrationService=e,this.paypalCommerceRequestSender=t,this.paypalSdkScriptLoader=i,this.paypalFastlaneUtils=n}initialize(e){var t,i;return lp(this,void 0,void 0,function*(){const{methodId:n,paypalcommercefastlane:r}=e;if(this.methodId=n,this.paypalcommercefastlane=r,!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.paypalcommercefastlane" argument is not provided.');if(!r.onInit||"function"!=typeof r.onInit)throw new gn('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 gn('Unable to initialize payment because "options.paypalcommercefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(n),{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);const l=qs(c?null===(i=null==s?void 0:s.initializationData)||void 0===i?void 0:i.fastlaneStyles:{},null==r?void 0:r.styles);yield this.paypalFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(n)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(n))})}execute(e,t){return lp(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{paymentData:r,methodId:o}=i,a=r&&gd(r);try{yield this.paymentIntegrationService.submitOrder(n,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 vd)}deinitialize(){return lp(this,void 0,void 0,function*(){return Promise.resolve()})}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getCustomerOrThrow(),n=e.getPaymentProviderCustomer(),r=cp(n)?n:{},o=this.paypalFastlaneUtils.getStorageSessionId();return!(!i.isGuest||(null==r?void 0:r.authenticationState)===Ms.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}runPayPalAuthenticationFlowOrThrow(e){return lp(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getCustomer(),r=t.getBillingAddress(),o=(null==n?void 0:n.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===Ms.CANCELED?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(i.id)}catch(e){}})}initializePayPalPaymentComponent(){return lp(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),t=e.phone,i=`${e.firstName} ${e.lastName}`.trim(),n=this.paypalFastlaneUtils.getPayPalFastlaneOrThrow(),r={fields:Object.assign({cardholderName:{prefill:i,enabled:!0}},t&&{phoneNumber:{prefill:t}})};this.paypalComponentMethods=yield n.FastlaneCardComponent(r)})}renderPayPalPaymentComponent(e){const t=this.getPayPalComponentMethodsOrThrow();if(!e)throw new gn('Unable to render card component because "container" argument is not provided.');t.render(e)}getPayPalComponentMethodsOrThrow(){if(!this.paypalComponentMethods)throw new pn;return this.paypalComponentMethods}prepareVaultedInstrumentPaymentPayload(e,t){return lp(this,void 0,void 0,function*(){const{instrumentId:i}=t,n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).config.is3dsEnabled?yield this.get3DSNonce(i):i;return yield this.createOrder(n),{methodId:e,paymentData:{formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:n}}}}})}preparePaymentPayload(e,t){return lp(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getBillingAddressOrThrow(),r=i.getPaymentMethodOrThrow(e),o=`${n.firstName} ${n.lastName}`.trim(),{getPaymentToken:a}=this.getPayPalComponentMethodsOrThrow(),{id:s}=yield a({name:{fullName:o},billingAddress:this.paypalFastlaneUtils.mapBcToPayPalAddress(n)}),d=r.config.is3dsEnabled?yield this.get3DSNonce(s):s;yield this.createOrder(d);const{shouldSaveInstrument:c=!1,shouldSetAsDefaultInstrument:l=!1}=_d(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 lp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getCartOrThrow().id;if(this.methodId){const{orderId:i}=yield this.paypalCommerceRequestSender.createOrder(this.methodId,{cartId:t,fastlaneToken:e});this.orderId=i}})}get3DSNonce(e){var t;return lp(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getCartOrThrow(),r=i.getOrderOrThrow(),o=i.getStoreConfigOrThrow().links.checkoutLink,a=null===(t=this.paypalFastlaneSdk)||void 0===t?void 0:t.ThreeDomainSecureClient;if(!a)throw new pn;const s={amount:r.orderAmount.toFixed(2),currency:n.currency.code,nonce:e,threeDSRequested:this.threeDSVerificationMethod===Os.Always,transactionContext:{experience_context:{locale:"en-US",return_url:o,cancel_url:o}}},d=yield a.isEligible(s);if(this.threeDSVerificationMethod===Os.Always&&!d)throw new Jr;if(d){const{liabilityShift:e,authenticationState:t,nonce:i}=yield a.show();if(e===is.No||e===is.Unknown||t===Es.Errored||t===Es.Cancelled)throw new Jr;if(t===Es.Succeeded&&[is.Yes,is.Possible].includes(e))return i}return e})}handlePayPalStoredInstrumentChange(e){return lp(this,void 0,void 0,function*(){const t=this.paypalFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:i,selectedCard:n}=yield t.profile.showCardSelector();if(i){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),i=cp(t)?t:{},r=this.paypalFastlaneUtils.mapPayPalToBcInstrument(e,n)[0];return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},i),{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 hp=Rt(e=>{const{getHost:t}=e.getState();return new up(e,new hs(i({host:t()})),Rs(),js())},[{id:"paypalcommerceacceleratedcheckout"}]);var pp,mp,yp,gp,vp,fp;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(pp||(pp={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(mp||(mp={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(yp||(yp={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(gp||(gp={})),function(e){e.PILL="pill",e.RECT="rect"}(vp||(vp={})),function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(fp||(fp={}));var Sp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class wp{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.useRedirectFlow=!1,this.window=window}initialize(e){return Sp(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 i=this.paymentMethod.config.merchantId;if(!this.isInContextEnabled()||!i)throw new Qi(Zi.MissingPaymentMethod);const n=yield this.scriptLoader.loadPaypalSDK();this.paypalSdk=n,this.paypalSdk.checkout.setup(i,{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 Sp(this,void 0,void 0,function*(){let i,n;const r=this.paypalSdk;if(!this.isAcknowledgedOrFinalized()){if(!this.isInContextEnabled()||this.useRedirectFlow)return i=yield this.paymentIntegrationService.submitOrder(e,t),n=i.getPaymentRedirectUrl(),n&&this.window.top&&(this.window.top.location.href=n),new Promise(V);if(!r)throw new nn(Xi.PaymentNotInitialized);r.checkout.initXO();try{i=yield this.paymentIntegrationService.submitOrder(e,t)}catch(e){return r.checkout.closeFlow(),Promise.reject(e)}return n=i.getPaymentRedirectUrl(),n&&r.checkout.startFlow(n),new Promise(V)}yield this.paymentIntegrationService.submitOrder(e,t)})}finalize(e){return Sp(this,void 0,void 0,function*(){return this.paymentIntegrationService.getState().getOrder()&&this.isAcknowledgedOrFinalized()?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new vd)})}isAcknowledgedOrFinalized(){const e=this.paymentIntegrationService.getState();return e.getPaymentStatus()===fp.ACKNOWLEDGE||e.getPaymentStatus()===fp.FINALIZE}isInContextEnabled(){return!(!this.paymentMethod||!this.paymentMethod.config.merchantId)}}class Ip{constructor(e){this.scriptLoader=e,this.window=window}loadPaypalSDK(e=""){return t=this,i=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 pn;return this.window.paypal},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}const _p=Rt(e=>new wp(e,new Ip(a())),[{id:"paypalexpress",type:"PAYMENT_TYPE_HOSTED"},{id:"paypalexpresscredit",type:"PAYMENT_TYPE_HOSTED"}]);var Cp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class bp extends Rl{constructor(e,t){super(e),this.paymentIntegrationService=e,this.threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Cp(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);i.config.is3dsEnabled&&(yield this.threeDSecureFlow.prepare(i))})}execute(e,t){const i=Object.create(null,{execute:{get:()=>super.execute}});return Cp(this,void 0,void 0,function*(){const{payment:{methodId:n=""}={}}=e,r=this.paymentIntegrationService.getState();return r.getPaymentStatus()===Gc.ACKNOWLEDGE?(yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:{methodId:n}}),t),Promise.resolve()):r.getPaymentMethodOrThrow(n).config.is3dsEnabled?this.threeDSecureFlow.start(i.execute.bind(this),e,t,this._hostedForm):i.execute.call(this,e,t)})}}const Pp=Rt(e=>new bp(e,new lu(e,new Su(new wu(a())))),[{id:"paypal"}]);class Op extends Rl{constructor(e,t){super(e),this.paymentIntegrationService=e,this._formPoster=t}execute(e,t){const{payment:i}=e;if(!i)throw new nn(Xi.PaymentNotInitialized);const{paymentData:n}=i;if(!n)throw new Qi(Zi.MissingPayment);if(this._isThreeDSTwoExperimentOn()){const t=Object.assign(Object.assign({},n),{browser_info:Xa()});e.payment&&(e.payment.paymentData=t)}return super.execute(e,t).catch(e=>ca(e)&&Z(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()===Gc.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),super.finalize()}_isThreeDSTwoExperimentOn(){return!0===this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features["INT-4994.Opayo_3DS2"]}}const Ep=Rt(e=>new Op(e,Ee()),[{id:"sagepay"}]);class Ap extends Tu{redirectUrl(e){window.location.replace(e)}}const Tp=Rt(e=>new Ap(Ee(),e),[{id:"sezzle"}]);var kp;!function(e){e.CHARGE="CHARGE",e.STORE="STORE"}(kp||(kp={}));var Dp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Mp{constructor(e,t){this._scriptLoader=e,this._paymentIntegrationService=t}initialize({testMode:e,applicationId:t,locationId:i}){return Dp(this,void 0,void 0,function*(){const n=yield this._scriptLoader.load(e);this._payments=n.payments(t,i)})}deinitialize(){return Dp(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:i}){return Dp(this,void 0,void 0,function*(){const{postalCode:n}=this._paymentIntegrationService.getState().getBillingAddress()||{};this._card=yield this._getPayments().card(),yield this._card.attach(`#${e}`);try{yield this._card.configure({postalCode:n,style:t})}catch(e){}i&&(this._formValidationSubscription=this._subscribeToFormValidation(this._card,i))})}tokenize(){return Dp(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 rh("payment.errors.card_error","SquareV2TokenizationError",t)}return e.token})}verifyBuyer(e,t){return Dp(this,void 0,void 0,function*(){return t===kp.CHARGE?this._chargeVerifyBuyer(e):this._storeVerifyBuyer(e)})}_getPayments(){return tn(this._payments,()=>new nn(Xi.PaymentNotInitialized))}_subscribeToFormValidation(e,t){const i=["cardNumber","cvv"],n=new Set(i),r=["focusClassAdded","focusClassRemoved","errorClassAdded","errorClassRemoved","cardBrandChanged","postalCodeChanged"].map(t=>ue(e,t));return he(...r).pipe(we(e=>{const{detail:{field:t,currentState:{isCompletelyValid:r}}}=e;return i.includes(t)&&n[r?"delete":"add"](t),0===n.size}),fe()).subscribe(t)}_getCard(){return tn(this._card,()=>new nn(Xi.PaymentNotInitialized))}_mapToSquareBillingContact({firstName:e,lastName:t,address1:i,address2:n,city:r,stateOrProvinceCode:o,postalCode:a,countryCode:s,email:d,phone:c}){return{givenName:e,familyName:t,addressLines:[i,n],city:r,state:o,postalCode:a,countryCode:s,email:d,phone:c}}_chargeVerifyBuyer(e){return Dp(this,void 0,void 0,function*(){const{getCheckoutOrThrow:t,getBillingAddressOrThrow:i}=this._paymentIntegrationService.getState(),{outstandingBalance:n,cart:r}=t(),o={amount:n.toString(),billingContact:this._mapToSquareBillingContact(i()),currencyCode:r.currency.code,intent:kp.CHARGE},a=yield this._getPayments().verifyBuyer(e,o);return a?a.token:""})}_storeVerifyBuyer(e){return Dp(this,void 0,void 0,function*(){const{getBillingAddressOrThrow:t}=this._paymentIntegrationService.getState(),i={billingContact:this._mapToSquareBillingContact(t()),intent:kp.STORE},n=yield this._getPayments().verifyBuyer(e,i);return n?n.token:""})}}var zp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Np{constructor(e,t){this._paymentIntegrationService=e,this._squareV2PaymentProcessor=t}initialize(e){var t;return zp(this,void 0,void 0,function*(){if(!(null===(t=null==e?void 0:e.squarev2)||void 0===t?void 0:t.containerId))throw new gn('Unable to proceed because "containerId" argument is not provided.');const{methodId:i,squarev2:n}=e,{config:{testMode:r},initializationData:o}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{applicationId:a,locationId:s}=o||{};if(!a)throw new Jr;yield this._squareV2PaymentProcessor.initialize({applicationId:a,locationId:s,testMode:r}),yield this._squareV2PaymentProcessor.initializeCard(n)})}execute({payment:e}){return zp(this,void 0,void 0,function*(){if(!e)throw new oo(["payment"]);const{methodId:t,paymentData:i}=e,{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:r}=_d(i)?i:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};yield this._paymentIntegrationService.submitOrder();const o=i&&gd(i)?yield this._getVaultedInstrumentPayload(t,i):yield this._getCardPayload(t,n);yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:Object.assign(Object.assign({},o),{vault_payment_instrument:n||!1,set_as_default_stored_instrument:r||!1})}}))})}finalize(){return Promise.reject(new vd)}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 zp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:i}=this._paymentIntegrationService.getState(),{initializationData:n}=i(e),r=yield this._squareV2PaymentProcessor.tokenize();if(n&&"isSquareV2ApiV2Enabled"in n?!n.isSquareV2ApiV2Enabled:!this.shouldVerify())return{credit_card_token:{token:r}};let o={nonce:r,token:yield this._squareV2PaymentProcessor.verifyBuyer(r,kp.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,kp.STORE)})}return{credit_card_token:{token:JSON.stringify(o)}}})}_getVaultedInstrumentPayload(e,t){return zp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:i}=this._paymentIntegrationService.getState(),{initializationData:n}=i(e),{instrumentId:r}=t,o=(n&&"isSquareV2ApiV2Enabled"in n?n.isSquareV2ApiV2Enabled:this.shouldVerify())?yield this._squareV2PaymentProcessor.verifyBuyer(yield this._getSquareCardIdOrThrow(e,r),kp.CHARGE):void 0;return{bigpay_token:Object.assign({token:r},o&&{three_d_secure:{token:o}})}})}_getSquareCardIdOrThrow(e,t){return zp(this,void 0,void 0,function*(){const i=yield this._paymentIntegrationService.loadPaymentMethod(e,{params:{method:e,bigpayToken:t}}),{initializationData:n}=i.getPaymentMethodOrThrow(e),{cardId:r}=n||{};if(!r)throw new oo(["cardId"]);return r})}}var xp;!function(e){e.LIVE="https://web.squarecdn.com/v1/square.js",e.SANDBOX="https://sandbox.web.squarecdn.com/v1/square.js"}(xp||(xp={}));class Fp{constructor(e){this._scriptLoader=e}load(e=!1){return t=this,i=void 0,r=function*(){return yield this._scriptLoader.loadScript(e?xp.SANDBOX:xp.LIVE),function(e){if(!function(e){return"Square"in e}(e))throw new pn}(window),window.Square},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}const Rp=Rt(e=>new Np(e,new Mp(new Fp(a()),e)),[{id:"squarev2"}]);function Lp(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 Bp,jp,Up,qp;!function(e){e.Solid="solid",e.Default="default"}(Bp||(Bp={})),function(e){e.Alipay="alipay",e.CardCvc="cardCvc",e.CardExpiry="cardExpiry",e.CardNumber="cardNumber",e.CreditCard="card",e.IDEAL="idealBank",e.Sepa="iban"}(jp||(jp={})),function(e){e.Alipay="alipay",e.CreditCard="card",e.IDEAL="ideal",e.Sepa="sepa_debit"}(Up||(Up={})),function(e){e.AuthFailure="auth_failure"}(qp||(qp={}));class Vp extends Ji{constructor(e){super(e===qp.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 Gp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};const Hp=[jp.Alipay,jp.IDEAL];class $p{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Gp(this,void 0,void 0,function*(){const{stripev3:t,methodId:i,gatewayId:n}=e;if(!n)throw new gn('Unable to initialize payment because "gatewayId" argument is not provided.');this.initializeOptions=t,this.isDeinitialize=!1;const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{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(i)&&this.shouldShowTSVHostedForm(i,n)&&c?this.hostedForm=yield this.mountCardVerificationFields(c):this.stripeElement=yield this.mountCardFields(i)})}execute(e,t){var i,n;return Gp(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);let a,s;if(!r||!r.paymentData)throw new oo(["payment.paymentData"]);const{paymentData:d,gatewayId:c,methodId:l}=r,{shouldSaveInstrument:u,shouldSetAsDefaultInstrument:h}=_d(d)?d:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},p=P(Hp,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(gd(d)){yield this.paymentIntegrationService.submitOrder(o,t);const{instrumentId:i}=d,n=e.getPaymentMethodOrThrow(r.methodId).clientToken;if(!n)throw new Qi(Zi.MissingPaymentMethod);return yield this.executeWithVaulted(r,i,h,n)}const m=e.getPaymentMethodOrThrow(l),y=yield this.confirmStripePayment(m),{clientToken:g,method:v}=m,{id:f}=null!==(n=null!==(i=y.paymentIntent)&&void 0!==i?i:y.paymentMethod)&&void 0!==n?n:{id:""};s=y.error,a={credit_card_token:{token:f},vault_payment_instrument:u,confirm:!1,set_as_default_stored_instrument:h},v===jp.CreditCard&&(a.client_token=g),p||(yield this.paymentIntegrationService.submitOrder(o,t));const S=this.buildPaymentPayload(l,a,h);yield this.paymentIntegrationService.submitPayment(S)}catch(e){yield this.processAdditionalAction(this.handleEmptyPaymentIntentError(e,s),l,u,h)}})}finalize(){return Promise.reject(new vd)}deinitialize(){return this.hostedForm&&this.hostedForm.detach(),this.isDeinitialize=!0,this.unmountElement(),Promise.resolve()}buildPaymentPayload(e,t,i){return{methodId:e,paymentData:i?{formattedPayload:Object.assign(Object.assign({},t),{set_as_default_stored_instrument:i})}:{formattedPayload:t}}}isCancellationError(e){var t,i;return e&&-1!==(null===(i=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===i?void 0:i.indexOf("canceled"))}isAuthError(e){return"payment_intent_authentication_failure"===(null==e?void 0:e.code)}isCreditCard(e){return e===Up.CreditCard}isHostedFieldAvailable(){var e;const t=this.getInitializeOptions(),i=H(null===(e=t.form)||void 0===e?void 0:e.fields,E);return!E(i)}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:i}=this.paymentIntegrationService.getState(),n=i(e,t);return Boolean(n.config.isHostedFormEnabled)}confirmStripePayment(e){return Gp(this,void 0,void 0,function*(){const{clientToken:t,method:i,returnUrl:n}=e;if(!t)throw new Qi(Zi.MissingPaymentMethod);switch(i){case jp.Alipay:return this.getStripeJs().confirmAlipayPayment(t,{return_url:n},{handleActions:!1});case jp.IDEAL:{const e=this.mapStripePaymentData(Up.IDEAL,n);return this.getStripeJs().confirmIdealPayment(t,e,{handleActions:!1})}case jp.Sepa:{const e=this.mapStripePaymentData(Up.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()),i=this._allowRedisplayForStoredInstruments;return this.getStripeJs().createPaymentMethod(Object.assign({type:Up.CreditCard,card:e,billing_details:t},i?{allow_redisplay:"always"}:{}))}}})}executeWithVaulted(e,t,i,n){var r;return Gp(this,void 0,void 0,function*(){const o={bigpay_token:{token:t},confirm:!0,client_token:n,set_as_default_stored_instrument:i};if(this.isHostedPaymentFormEnabled(e.methodId,e.gatewayId)&&this.hostedForm){const t=this.hostedForm;return e.paymentData&&gd(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:n})})),yield t.validate(),yield t.submit(e),this.paymentIntegrationService.loadCurrentOrder()}const a=this.buildPaymentPayload(e.methodId,o,i);return this.paymentIntegrationService.submitPayment(a)})}getInitializeOptions(){if(!this.initializeOptions)throw new nn(Xi.PaymentNotInitialized);return this.initializeOptions}getStripeCardElements(){if(!this.stripeCardElements)throw new nn(Xi.PaymentNotInitialized);return this.stripeCardElements}getStripeElement(){if(!this.stripeElement)throw new nn(Xi.PaymentNotInitialized);return this.stripeElement}getStripeJs(){if(!this.stripeV3Client)throw new nn(Xi.PaymentNotInitialized);return this.stripeV3Client}handleEmptyPaymentIntentError(e,t){return ca(e)&&Z(e.body.errors,{code:"required_field"})&&t?new Error(t.message):e}loadStripeJs(e,t){return Gp(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:i,address1:n,address2:r,postalCode:o,stateOrProvinceCode:a}=e;return{city:t,country:i,line1:n,line2:r,postal_code:o,state:a}}return{line1:""}}mapStripeBillingDetails(e,t){const{firstName:i,lastName:n}=e||t||{firstName:"Guest",lastName:""},r=`${i} ${n}`.trim(),{options:o}=this.getInitializeOptions();if(this.useIndividualCardFields&&Lp(o)){const{zipCodeElementOptions:t}=o;if(t){const i=document.getElementById(t.containerId)?document.getElementById(t.containerId).value:"";i&&e&&(e=Object.assign(Object.assign({},e),{postalCode:i}))}}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:i}=t,{phone:n}=e;return n?Object.assign(Object.assign({},a),{email:i,name:r,phone:n}):Object.assign(Object.assign({},a),{email:i,name:r})}if(e){const{email:t,phone:i}=e;return i?Object.assign(Object.assign({},a),{email:t,name:r,phone:i}):Object.assign(Object.assign({},a),{email:t,name:r})}return Object.assign(Object.assign({},a),{name:r})}mapStripePaymentData(e,t){const i=this.paymentIntegrationService.getState().getCustomer(),n=this.paymentIntegrationService.getState().getBillingAddress(),r={payment_method:{[e]:this.getStripeElement(),billing_details:this.mapStripeBillingDetails(n,i)}};return e===Up.IDEAL?Object.assign(Object.assign({},r),{return_url:t}):r}mountCardFields(e){const{options:t,containerId:i}=this.getInitializeOptions();let n;return new Promise((r,o)=>{switch(this.stripeElements||(this.stripeElements=this.getStripeJs().elements()),e){case jp.CreditCard:if(this.useIndividualCardFields&&Lp(t)){const{cardNumberElementOptions:e,cardExpiryElementOptions:i,cardCvcElementOptions:r}=t,a=this.stripeElements.getElement(jp.CardNumber)||this.stripeElements.create(jp.CardNumber,e),s=this.stripeElements.getElement(jp.CardExpiry)||this.stripeElements.create(jp.CardExpiry,i),d=this.stripeElements.getElement(jp.CardCvc)||this.stripeElements.create(jp.CardCvc,r);this.stripeCardElements=[a,s,d],n=this.stripeCardElements[0];try{a.mount(`#${e.containerId}`),s.mount(`#${i.containerId}`),d.mount(`#${r.containerId}`)}catch(e){this.isDeinitialize||o(new gn("Unable to mount Stripe component without valid container ID."))}}else{n=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{n.mount(`#${i}`)}catch(e){this.isDeinitialize||o(new gn("Unable to mount Stripe component without valid container ID."))}}break;case jp.IDEAL:case jp.Sepa:n=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{n.mount(`#${i}`)}catch(e){this.isDeinitialize||o(new gn("Unable to mount Stripe component without valid container ID."))}case jp.Alipay:}r(n)})}mountCardVerificationFields(e){return Gp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getStoreConfig();if(!t)throw new Qi(Zi.MissingCheckoutConfig);const i=t.paymentSettings.bigpayBaseUrl,n=this.paymentIntegrationService.createHostedForm(i,e);return yield n.attach(),n})}processAdditionalAction(e,t,i=!1,n=!1){return Gp(this,void 0,void 0,function*(){if(!ca(e))throw e;const r=Z(e.body.errors,{code:"additional_action_required"}),o=Z(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 Vn;if(this.isAuthError(a.error))throw new Vp(qp.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:i,confirm:o},c=this.buildPaymentPayload(t,d,n);try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){throw this.handleEmptyPaymentIntentError(e,null==a?void 0:a.error)}}throw e})}getPaymentToken(e,t,i){return!e||i?t:e.id}shouldShowTSVHostedForm(e,t){return this.isHostedFieldAvailable()&&this.isHostedPaymentFormEnabled(e,t)}unmountElement(){this.stripeElement&&(this.stripeElement.unmount(),this.stripeElement=void 0)}}class Wp{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}load(e,t,i){return this.scriptLoader.loadScript("https://js.stripe.com/v3/").then(()=>{if(!this.stripeWindow.Stripe)throw new pn;return this.stripeWindow.Stripe(e,{stripeAccount:t,locale:i,betas:["payment_intent_beta_3","alipay_pm_beta_1"],apiVersion:"2020-03-02;alipay_beta=v1"})})}}const Yp=Rt(e=>new $p(e,new Wp(a())),[{gateway:"stripev3"}]),Kp={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 Jp(e){const[t,i]=e.replace(/_/g,"-").toLowerCase().split("-"),n=Kp[t];if(!n)return"auto";const r=i?`${t}-${i.toUpperCase()}`:t;return n.indexOf(r)>-1?r:n[0]}var Zp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Xp{constructor(e,t,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=i}initialize(e){return Zp(this,void 0,void 0,function*(){const{stripeupe:t,methodId:i,gatewayId:n}=e;if(!(null==t?void 0:t.containerId))throw new nn(Xi.PaymentNotInitialized);if(!n)throw new gn('Unable to initialize payment because "gatewayId" argument is not provided.');return this._loadStripeElement(t,n,i).catch(e=>{var i;return null===(i=t.onError)||void 0===i?void 0:i.call(t,e)}),this.stripeIntegrationService.initCheckoutEventsSubscription(n,i,t,this._stripeElements),Promise.resolve()})}execute(e,t){return Zp(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i||!i.paymentData)throw new oo(["payment.paymentData"]);if(!this._stripeUPEClient)throw new nn(Xi.PaymentNotInitialized);const{paymentData:r,methodId:o,gatewayId:a}=i,{shouldSaveInstrument:s=!1,shouldSetAsDefaultInstrument:d=!1}=_d(r)?r:{},c=this.paymentIntegrationService.getState(),{isStoreCreditApplied:l}=c.getCheckoutOrThrow(),u=c.getPaymentProviderCustomerOrThrow(),h=(Ws(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(n,t),gd(r)){const{instrumentId:e}=r;return void(yield this._executeWithVaulted(i.methodId,e,d))}yield this._executeWithStripeConfirmation(i.methodId,!h&&s,d)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Pa.PAYMENT))||void 0===t||t.unmount(),this.stripeIntegrationService.deinitialize(),this._stripeElements=void 0,this._stripeUPEClient=void 0,Promise.resolve()}_executeWithStripeConfirmation(e,t,i){return Zp(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),{clientToken:r}=n.getPaymentMethodOrThrow(e),o=this._getPaymentPayload(e,r||"",t,i);try{yield this.paymentIntegrationService.submitPayment(o)}catch(n){yield this._processAdditionalActionWithStripeConfirmation(n,e,t,i)}})}_executeWithVaulted(e,t,i){var n;return Zp(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(e),a=null===(n=r.getCart())||void 0===n?void 0:n.id;try{const n={methodId:e,paymentData:{formattedPayload:{cart_id:a,bigpay_token:{token:t},confirm:!1,client_token:o.clientToken,set_as_default_stored_instrument:i}}};return yield this.paymentIntegrationService.submitPayment(n)}catch(t){return this._processVaultedAdditionalAction(t,e,i)}})}_loadStripeElement(e,t,i){return Zp(this,void 0,void 0,function*(){const{containerId:n,style:r,render:o,initStripeElementUpdateTrigger:a}=e,s=yield this.paymentIntegrationService.loadPaymentMethod(t,{params:{method:i}}),d=s.getPaymentMethodOrThrow(i);if(!$s(d))throw new Qi(Zi.MissingPaymentMethod);const{clientToken:c,initializationData:l}=d,{shopperLanguage:u,allowRedisplayForStoredInstruments:h=!1,enableLink:p}=l;if(this._allowRedisplayForStoredInstruments=h,!c)throw new Qi(Zi.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:Jp(u),appearance:m});const{getBillingAddress:y,getShippingAddress:g}=s,{postalCode:v}=g()||y()||{},f=this._stripeElements.getElement(Pa.PAYMENT)||this._stripeElements.create(Pa.PAYMENT,Object.assign({fields:{billingDetails:{email:Ca.NEVER,address:{country:Ca.NEVER,city:Ca.NEVER,postalCode:v?Ca.NEVER:Ca.AUTO}}},wallets:{applePay:Ca.NEVER,googlePay:Ca.NEVER,link:p?Ca.AUTO:Ca.NEVER}},this._getStripeElementTerms()));this.stripeIntegrationService.mountElement(f,n),f.on(Ea.READY,()=>{o()}),f.on(Ea.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,i=!1,n=!1){return Zp(this,void 0,void 0,function*(){if(!ca(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new nn(Xi.PaymentNotInitialized);const{data:r}=e.body.additional_action_required,{token:o}=r,{paymentIntent:a}=yield this._confirmStripePaymentOrThrow(t,r),s=this._getPaymentPayload(t,(null==a?void 0:a.id)||o,i,n);try{yield this.paymentIntegrationService.submitPayment(s)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){var i,n;return Zp(this,void 0,void 0,function*(){const{token:r,redirect_url:o}=t,a=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,o,!!this._allowRedisplayForStoredInstruments);let s;try{const t=(yield this.stripeIntegrationService.isPaymentCompleted(e,this._stripeUPEClient))?yield null===(n=this._stripeUPEClient)||void 0===n?void 0:n.retrievePaymentIntent(r||""):yield null===(i=this._stripeUPEClient)||void 0===i?void 0:i.confirmPayment(a);if(s=null==t?void 0:t.error,s||!(null==t?void 0:t.paymentIntent))throw new Kr;return t}catch(e){this.stripeIntegrationService.throwStripeError(s)}})}_processVaultedAdditionalAction(e,t,i=!1){var n;return Zp(this,void 0,void 0,function*(){if(!t||!ca(e)||!Z(e.body.errors,{code:"three_d_secure_required"}))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new nn(Xi.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 Qn;const s=this._getPaymentPayload(t,a?r:null===(n=null==o?void 0:o.paymentIntent)||void 0===n?void 0:n.id,!1,i);return this.paymentIntegrationService.submitPayment(s)})}_loadStripeJs(e){return Zp(this,void 0,void 0,function*(){if(this._stripeUPEClient)return this._stripeUPEClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ba.V3,Da,Ma)})}_getPaymentPayload(e,t,i=!1,n=!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:i,set_as_default_stored_instrument:n}}}}_updateStripeElement({shouldShowTerms:e}){var t;const i=null===(t=this._stripeElements)||void 0===t?void 0:t.getElement(Pa.PAYMENT);null==i||i.update(Object.assign({},this._getStripeElementTerms(e)))}_getStripeElementTerms(e){let t=Ca.AUTO;return this._isStripeElementUpdateEnabled&&(t=e?Ca.AUTO:Ca.NEVER),{terms:{card:t}}}_updateStripeLinkStateByElementType(e){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),i=e===_a.Link;!Ws(t)&&i&&this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:i})}}const Qp=Rt(e=>{const t=new ka(a());return new Xp(e,t,new Zs(e,t))},[{gateway:"stripeupe"},{gateway:"stripeupe",id:"klarna"}]);var em=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class tm{constructor(e,t,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=i}initialize(e){var t;return em(this,void 0,void 0,function*(){const{stripeocs:i,methodId:n,gatewayId:r}=e;if(!(null==i?void 0:i.containerId))throw new nn(Xi.PaymentNotInitialized);if(!r)throw new gn('Unable to initialize payment because "gatewayId" argument is not provided.');try{yield this._initializeStripeElement(i,r,n)}catch(e){e instanceof Error&&(null===(t=i.onError)||void 0===t||t.call(i,e))}this.stripeIntegrationService.initCheckoutEventsSubscription(r,n,i,this.stripeElements)})}execute(e,t){return em(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{methodId:r,gatewayId:o}=i||{};if(!this.stripeClient)throw new nn(Xi.PaymentNotInitialized);if(!o||!r)throw new gn('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(n,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)}})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Pa.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,i){return em(this,void 0,void 0,function*(){let n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,t);if((null==n?void 0:n.clientToken)||(n=(yield this.paymentIntegrationService.loadPaymentMethod(t,{params:{method:i}})).getPaymentMethodOrThrow(i,t)),!$s(n))throw new Qi(Zi.MissingPaymentMethod);const{clientToken:r,initializationData:o}=n,{shopperLanguage:a,customerSessionToken:s,enableLink:d}=o;if(!r)throw new Qi(Zi.MissingPaymentMethod);this.stripeClient=yield this._loadStripeJs(o);const{appearance:c,containerId:l,fonts:u,layout:h,render:p,paymentMethodSelect:m,handleClosePaymentMethod:y,togglePreloader:g}=e;this.stripeElements=yield this.scriptLoader.getElements(this.stripeClient,{clientSecret:r,customerSessionClientSecret:s,locale:Jp(a),appearance:c,fonts:u});const{getBillingAddress:v,getShippingAddress:f}=this.paymentIntegrationService.getState(),S=v(),{postalCode:w}=f()||S||{},I=this.stripeElements.getElement(Pa.PAYMENT)||this.stripeElements.create(Pa.PAYMENT,{fields:{billingDetails:{email:Ca.NEVER,address:{country:Ca.NEVER,city:Ca.NEVER,postalCode:w?Ca.NEVER:Ca.AUTO}}},wallets:{applePay:Ca.NEVER,googlePay:Ca.NEVER,link:d?Ca.AUTO:Ca.NEVER},layout:h,savePaymentMethod:{maxVisiblePaymentMethods:20},defaultValues:{billingDetails:{email:(null==S?void 0:S.email)||""}}});this.stripeIntegrationService.mountElement(I,l),I.on(Ea.LOADER_START,()=>{null==g||g(!1)}),I.on(Ea.READY,()=>{p()}),I.on(Ea.CHANGE,e=>{this._onStripeElementChange(e,t,i,m)}),null==y||y(this._collapseStripeElement.bind(this))})}_loadStripeJs(e){return em(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState(),i=this.stripeIntegrationService.getStripeJsVersion(e);return this.scriptLoader.getStripeClient(e,t.getCartLocale(),i)})}_collapseStripeElement(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Pa.PAYMENT);null==t||t.collapse()}_getPaymentPayload(e,t,i){var n;const r=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"",{card:o,us_bank_account:a}=i||{},s=this._shouldSaveInstrument(o)||this._shouldSaveInstrument(a),d=this._getTokenizedOptions(t,i);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:s},d)}}}_processAdditionalAction(e,t){return em(this,void 0,void 0,function*(){if(!ca(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this.stripeClient||!this.stripeElements)throw new nn(Xi.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:n}=i,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(t,i),{client_secret:o,payment_method_options:a}=r||{},s=this._getPaymentPayload(t,o||n,a);try{return yield this.paymentIntegrationService.submitPayment(s)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){var i,n;return em(this,void 0,void 0,function*(){const{token:r,redirect_url:o}=t,a=this.stripeIntegrationService.mapStripePaymentData(this.stripeElements,o);let s;try{const t=(yield this.stripeIntegrationService.isPaymentCompleted(e,this.stripeClient))?yield null===(n=this.stripeClient)||void 0===n?void 0:n.retrievePaymentIntent(r||""):yield null===(i=this.stripeClient)||void 0===i?void 0:i.confirmPayment(a);if(s=null==t?void 0:t.error,s||!(null==t?void 0:t.paymentIntent))throw new Kr;return t}catch(e){return this.stripeIntegrationService.throwStripeError(s)}})}_onStripeElementChange(e,t,i,n){(e=>"object"==typeof e&&null!==e&&"value"in e&&"collapsed"in e)(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==n||n(`${t}-${i}`))}_shouldSaveInstrument(e){const t=null==e?void 0:e.setup_future_usage;return t===Aa.ON_SESSION||t===Aa.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 im=Rt(e=>{const t=new ka(a());return new tm(e,t,new Zs(e,t))},[{gateway:"stripeocs",id:"optimized_checkout"}]);var nm=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class rm{constructor(e,t,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=i}initialize(e){var t;return nm(this,void 0,void 0,function*(){const{stripeocs:i,methodId:n,gatewayId:r}=e;if(!(null==i?void 0:i.containerId)||!r)throw new nn(Xi.PaymentNotInitialized);try{yield this._initializeStripeElement(i,r,n)}catch(e){e instanceof Error&&(null===(t=i.onError)||void 0===t||t.call(i,e))}this.stripeIntegrationService.initCheckoutEventsSubscription(r,n,i,this.stripeElements)})}execute(){return nm(this,void 0,void 0,function*(){return Promise.resolve()})}finalize(){return Promise.reject(new vd)}deinitialize(){return Promise.resolve()}_initializeStripeElement(e,t,i){return nm(this,void 0,void 0,function*(){let e=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,t);if((null==e?void 0:e.clientToken)||(e=(yield this.paymentIntegrationService.loadPaymentMethod(t,{params:{method:i}})).getPaymentMethodOrThrow(i,t)),!$s(e))throw new Qi(Zi.MissingPaymentMethod);const{clientToken:n,initializationData:r}=e;if(!n)throw new Qi(Zi.MissingPaymentMethod);this.stripeClient=yield this._loadStripeJs(r)})}_loadStripeJs(e){return nm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ba.CLOVER)})}}const om=Rt(e=>{const t=new ka(a());return new rm(e,t,new Zs(e,t))},[{gateway:"stripeocs",id:"checkout_session"}]);var am;!function(e){e.CARD_NUMBER="card-number",e.CVV="cvv",e.EXPIRY="expiry"}(am||(am={}));var sm=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class dm{constructor(e,t,i){this.paymentIntegrationService=e,this.tdOnlineMartScriptLoader=t,this.formPoster=i,this.tdInputs=[{id:"ccNumber",fieldType:am.CARD_NUMBER},{id:"ccCvv",fieldType:am.CVV},{id:"ccExpiry",fieldType:am.EXPIRY}]}initialize(e){return sm(this,void 0,void 0,function*(){const{methodId:t}=e;if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');this.tdOnlineMartClient=yield this.loadTDOnlineMartJs(),this.mountHostedFields(t)})}execute(e,t){return sm(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);if(!i.methodId)throw new Qi(Zi.MissingPaymentMethod);const r=yield this.getPaymentPayloadOrThrow(i);yield this.paymentIntegrationService.submitOrder(n,t);try{yield this.paymentIntegrationService.submitPayment(r)}catch(e){yield this.processWithAdditionalAction(e)}})}finalize(){return Promise.reject(new vd)}deinitialize(){return this.tdOnlineMartClient=void 0,this.tdInputs.forEach(({inputElement:e})=>{null==e||e.unmount()}),Promise.resolve()}getPaymentPayloadOrThrow(e){return sm(this,void 0,void 0,function*(){const{methodId:t,paymentData:i}=e,{shouldSaveInstrument:n=!1,shouldSetAsDefaultInstrument:r=!1}=_d(i)?i:{},o={browser_info:Xa(),shouldSaveInstrument:n,shouldSetAsDefaultInstrument:r};if(_d(i)&&gd(i)&&i.instrumentId){const e=!!this.paymentIntegrationService.getState().getCartOrThrow().lineItems.digitalItems.length,n=!this.isTrustedVaultingInstrument(i.instrumentId)||e;return{methodId:t,paymentData:Object.assign(Object.assign(Object.assign({},o),{instrumentId:i.instrumentId}),n?{nonce:i.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(),i=this.getTDOnlineMartClientOrThrow();this.tdInputs.forEach(n=>{const r=`${e}-${n.id}`;document.getElementById(r)&&(n.inputElement=i.create(n.fieldType,t),n.inputElement.mount(`#${r}`))})}loadTDOnlineMartJs(){return sm(this,void 0,void 0,function*(){return this.tdOnlineMartClient?this.tdOnlineMartClient:this.tdOnlineMartScriptLoader.load()})}getTokenOrThrow(){return new Promise((e,t)=>{this.getTDOnlineMartClientOrThrow().createToken(i=>{const{error:n,token:r}=i;if(n||!r)return t(n);e(r)})})}getTDOnlineMartClientOrThrow(){if(!this.tdOnlineMartClient)throw new nn(Xi.PaymentNotInitialized);return this.tdOnlineMartClient}processWithAdditionalAction(e){return sm(this,void 0,void 0,function*(){if(!function(e){return ca(e)&&(t=e.body,D(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&O(t.errors)&&Z(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:i,payer_auth_request:n,merchant_data:r}=t||{};if(!i||!n||!r)throw new oo(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(i,{threeDSSessionData:n,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 Qi(Zi.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(),i=null==t?void 0:t.find(t=>Wd(t)&&t.bigpayToken===e);return!(Wd(i)&&!i.trustedShippingAddress)}}class cm{constructor(e,t=window){this.scriptLoader=e,this.tdOnlineMartWindow=t}load(){return e=this,t=void 0,n=function*(){if(this.tdOnlineMartWindow.customcheckout||(yield this.scriptLoader.loadScript("https://libs.na.bambora.com/customcheckout/1/customcheckout.js")),!this.tdOnlineMartWindow.customcheckout)throw new pn;return this.tdOnlineMartWindow.customcheckout()},new((i=void 0)||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())});var e,t,i,n}}const lm=Rt(e=>new dm(e,new cm(a()),Ee()),[{id:"tdonlinemart"}]);var um=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};const hm="Payment cannot continue";let pm;class mm extends Rl{initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return um(this,void 0,void 0,function*(){if(this._initializeOptions=e&&e.worldpay,!this._initializeOptions)throw new nn(Xi.PaymentNotInitialized);return t.initialize.call(this,e)})}execute(e,t){const i=Object.create(null,{execute:{get:()=>super.execute}});return um(this,void 0,void 0,function*(){const{payment:n}=e;if(pm=this._submitAdditionalAction(),!n)throw new oo(["payment"]);try{return yield i.execute.call(this,e,t)}catch(e){return this._processAdditionalAction(e,n)}})}_processAdditionalAction(e,t){return um(this,void 0,void 0,function*(){return ca(e)&&Z(e.body.errors,{code:"additional_action_required"})?new Promise((i,n)=>{const r=e=>um(this,void 0,void 0,function*(){if(-1===e.origin.indexOf("cardinalcommerce.com"))return;if("string"!=typeof e.data||!this._isValidJsonWithSessionId(e.data))return n(new Error(hm));window.removeEventListener("message",r),o.remove();const a=JSON.parse(e.data),s=q({},t,{paymentData:{threeDSecure:{token:a.SessionId}}});try{i(yield pm(s))}catch(e){if(!ca(e)||!Z(e.body.errors,{code:"three_d_secure_required"}))return n(e);if(!this._initializeOptions)return n(new nn(Xi.PaymentNotInitialized));const{onLoad:t}=this._initializeOptions,i=this._createIframe(e.body.three_ds_result);try{t(i,()=>n(new Error("Payment was cancelled")))}catch(e){n(new Error(hm))}}});let o;window.addEventListener("message",r);try{o=this._createHiddenIframe(e.body)}catch(e){throw window.removeEventListener("message",r),new Error(hm)}}):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 i=document.createElement("form"),n="collectionForm";i.id=n,i.name="devicedata",i.method="post";const r=e.additional_action_required.data.redirect_url;i.action=r;const o=document.createElement("input");o.name="Bin",o.type="hidden",o.value=e.provider_data.source_id,i.appendChild(o);const a=document.createElement("input");a.name="JWT",a.type="hidden",a.value=e.provider_data.data,i.appendChild(a);const s=document.createElement("button");s.type="submit",s.id="btnsubmit",i.appendChild(s),navigator.userAgent.match("Firefox")?t.srcdoc=i.outerHTML:t.contentWindow.document.body.appendChild(i);const d=document.createElement("script");return d.innerHTML=`\n document.getElementById('${n}').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 i=document.createElement("input");i.name="JWT",i.type="hidden",i.value=e.payer_auth_request,t.appendChild(i);const n=document.createElement("input");n.name="MD",n.type="hidden",n.value=`merchantSessionId=${e.merchant_data}`,t.appendChild(n);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 nn(Xi.PaymentNotInitialized);const e=this._hostedForm;return t=>um(this,void 0,void 0,function*(){yield e.submit(t)})}return e=>um(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 ym=Rt(e=>new mm(e),[{id:"worldpayaccess"}]);class gm{constructor(e){this._requestSender=e}saveExternalId(e,t){return i=this,n=void 0,o=function*(){const i=`/api/storefront/payment/${e}/save-external-id`,n={headers:Object.assign({Accept:ur.JsonV1,"X-API-INTERNAL":cr},hr),body:{externalId:t,provider:e}};yield this._requestSender.post(i,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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}class vm{constructor(e,t){this.paymentIntegrationService=e,this.storefrontPaymentRequestSender=t}initialize(){return Promise.resolve()}execute(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{methodId:r}=i,{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 Qi(Zi.MissingPaymentMethod);const{id:c}=JSON.parse(a);if(!c)throw new Qi(Zi.MissingPaymentToken);const{isStoreCreditApplied:l}=this.paymentIntegrationService.getState().getCheckoutOrThrow();yield this.paymentIntegrationService.applyStoreCredit(l),yield this.paymentIntegrationService.initializePayment(r,{useStoreCredit:l}),yield this.paymentIntegrationService.submitOrder(n,t),yield this._prepareForReferredRegistration(r,c);try{yield this.paymentIntegrationService.submitPayment({methodId:r,paymentData:{nonce:c}})}catch(e){if(ca(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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}deinitialize(){return Promise.resolve()}_prepareForReferredRegistration(e,t){return this.storefrontPaymentRequestSender.saveExternalId(e,t)}}const fm=Rt(e=>{const{getHost:t}=e.getState(),n=i({host:t()}),r=new gm(n);return new vm(e,r)},[{id:"zip"},{id:"quadpay"}]);var Sm,wm;!function(e){e.LoadCountriesRequested="LOAD_COUNTRIES_REQUESTED",e.LoadCountriesSucceeded="LOAD_COUNTRIES_SUCCEEDED",e.LoadCountriesFailed="LOAD_COUNTRIES_FAILED"}(Sm||(Sm={}));class Im{constructor(e){this._countryRequestSender=e}loadCountries(e){return oe.create(t=>{t.next(l(Sm.LoadCountriesRequested)),this._countryRequestSender.loadCountries(e).then(e=>{t.next(l(Sm.LoadCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Sm.LoadCountriesFailed,e))})})}}class _m{constructor(e,t){this._requestSender=e,this._config=t}loadCountries({timeout:e}={}){const t=Object.assign({"Accept-Language":this._config.locale},rt);return this._requestSender.get("/internalapi/v1/store/countries",{headers:t,timeout:e})}}class Cm extends Ze{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 bm extends Ze{constructor(e){super(e||"The tax provider is unavailable."),this.name="OrderTaxProviderUnavailableError",this.type="tax_provider_unavailable"}}class Pm extends Ze{constructor(e){super(e),this.name="MissingShippingMethodError",this.type="missing_shipping_method"}}class Om extends Ze{constructor(e){super(e),this.name="InvalidShippingAddressError",this.type="invalid_shipping_address"}}class Em{constructor(e){this._requestSender=e}loadOrder(e,{timeout:t}={}){const i=`/api/storefront/orders/${e}`,n=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.get(i,{params:{include:Mt(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:n,timeout:t})}submitOrder(e,{headers:t,timeout:i}={}){return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:H(Object.assign({"X-Checkout-Variant":t&&t.checkoutVariant},rt),k),timeout:i}).catch(e=>{if("tax_provider_unavailable"===e.body.type)throw new bm;if("cart_has_changed"===e.body.type)throw new Cm;if("missing_shipping_method"===e.body.type)throw new Pm(e.body.detail);if("invalid_shipping_address"===e.body.type)throw new Om(e.body.detail);if("empty_cart"===e.body.type)throw new it;throw e})}finalizeOrder(e,{timeout:t}={}){const i=`/internalapi/v1/checkout/order/${e}`;return this._requestSender.post(i,{timeout:t,headers:rt})}}class Am extends Ze{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"}(wm||(wm={}));var Tm;class km{constructor(e,t){this._orderRequestSender=e,this._checkoutValidator=t}loadOrder(e,t){return new oe(i=>{i.next(l(wm.LoadOrderRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{i.next(l(wm.LoadOrderSucceeded,e.body)),i.complete()}).catch(e=>{i.error(h(wm.LoadOrderFailed,e))})})}loadOrderPayments(e,t){return new oe(i=>{i.next(l(wm.LoadOrderPaymentsRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{i.next(l(wm.LoadOrderPaymentsSucceeded,e.body)),i.complete()}).catch(e=>{i.error(h(wm.LoadOrderPaymentsFailed,e))})})}loadCurrentOrder(e){return t=>de(()=>{const i=this._getCurrentOrderId(t.getState());if(!i)throw new Xe(We.MissingOrderId);return this.loadOrder(i,e)})}submitOrder(e,t){return i=>se(me(l(wm.SubmitOrderRequested)),de(()=>{const n=i.getState(),r=n.config.getExternalSource(),o=n.config.getVariantIdentificationToken(),a=n.checkout.getCheckout();if(!a)throw new Xe(We.MissingCheckout);if(a.shouldExecuteSpamCheck)throw new Am;return le(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(Ce(e=>se(this.loadOrder(e.body.data.order.orderId,t),me(l(wm.SubmitOrderSucceeded,e.body.data,Object.assign(Object.assign({},e.body.meta),{token:e.headers.token}))))))}).pipe(ge(e=>Je(wm.SubmitOrderFailed,e))))}finalizeOrder(e,t){return se(me(l(wm.FinalizeOrderRequested)),le(this._orderRequestSender.finalizeOrder(e,t)).pipe(Ce(i=>se(this.loadOrder(e,t),me(l(wm.FinalizeOrderSucceeded,i.body.data)))))).pipe(ge(e=>Je(wm.FinalizeOrderFailed,e)))}_getCurrentOrderId(e){const t=e.order.getOrder(),i=e.checkout.getCheckout();return t&&t.orderId||i&&i.orderId}_mapToOrderRequestBody(e,t,i,n){const{payment:r}=e,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);return r?Object.assign(Object.assign({},o),{cartId:t,customerMessage:i,externalSource:n,payment:{paymentData:r.paymentData,name:r.methodId,gateway:r.gatewayId}}):Object.assign(Object.assign({},o),{cartId:t,customerMessage:i,externalSource:n})}}function Dm(e){const t=ke();return e.subscribe(e=>{const i=e.config.getStoreConfig();i&&t.setHost(i.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"}(Tm||(Tm={}));const Mm=e=>!!e;class zm{constructor(e){this._requestSender=e}loadPaymentMethodsById(e,t){return i=>new oe(n=>{var r;const o=null===(r=i.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);n.next(l(Tm.LoadPaymentMethodsRequested)),Promise.all(e.map(e=>{return i=this,n=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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).then(e=>{const t=e.filter(Mm);n.next(l(Tm.LoadPaymentMethodsSucceeded,t)),n.complete()}).catch(e=>{n.next(l(Tm.LoadPaymentMethodsFailed,e)),n.complete()})})}loadPaymentMethods(e){return t=>oe.create(i=>{const n=t.getState().cart.getCartOrThrow();i.next(l(Tm.LoadPaymentMethodsRequested)),this._requestSender.loadPaymentMethods(Object.assign(Object.assign({},e),{params:Object.assign(Object.assign({},null==e?void 0:e.params),{cartId:n.id})})).then(e=>{const t={deviceSessionId:e.headers["x-device-session-id"],sessionHash:e.headers["x-session-hash"]},n=e.body;i.next(l(Tm.LoadPaymentMethodsSucceeded,n,t)),i.complete()}).catch(e=>{i.error(h(Tm.LoadPaymentMethodsFailed,e))})})}loadPaymentMethod(e,t){return i=>oe.create(n=>{var r;const o=null===(r=i.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);n.next(l(Tm.LoadPaymentMethodRequested,void 0,{methodId:e})),this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a})).then(t=>{n.next(l(Tm.LoadPaymentMethodSucceeded,t.body,{methodId:e})),n.complete()}).catch(t=>{n.error(h(Tm.LoadPaymentMethodFailed,t,{methodId:e}))})})}}!function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);o>3&&a&&Object.defineProperty(t,i,a)}([vt],zm.prototype,"loadPaymentMethod",null);class Nm{constructor(e){this._requestSender=e}loadPaymentMethods({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/payments",{timeout:e,headers:Object.assign({Accept:nt.JsonV1,"X-API-INTERNAL":Ct},rt),params:t})}loadPaymentMethod(e,{timeout:t,params:i}={}){const n=`/api/storefront/payments/${e}`;return this._requestSender.get(n,{timeout:t,headers:Object.assign({Accept:nt.JsonV1,"X-API-INTERNAL":Ct},rt),params:i})}}class xm extends Ze{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var Fm,Rm;!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"}(Fm||(Fm={})),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.LAYBUY="laybuy",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"}(Rm||(Rm={}));const Lm=Rm;class Bm{widgetInteraction(e,t){const i={methodId:t&&t.methodId};return se(me(l(Fm.WidgetInteractionStarted,void 0,i)),de(()=>e().then(()=>l(Fm.WidgetInteractionFinished,void 0,i)))).pipe(ge(e=>Je(Fm.WidgetInteractionFailed,e,i)))}}class jm{constructor(e,t,i,n,r,o){this._strategyRegistry=e,this._strategyRegistryV2=t,this._orderActionCreator=i,this._spamProtectionActionCreator=n,this._paymentIntegrationService=r,this._errorLogger=o,this._paymentStrategyWidgetActionCreator=new Bm}execute(e,t){const{payment:i={},useStoreCredit:n}=e,r={methodId:i.methodId};return o=>{const{checkout:a}=o.getState(),{shouldExecuteSpamCheck:s}=a.getCheckoutOrThrow();return se(s?this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(o):ce(),me(l(Fm.ExecuteRequested,void 0,r)),de(()=>{const a=o.getState();let s;if(a.payment.isPaymentDataRequired(n)){const e=a.paymentMethods.getPaymentMethod(i.methodId,i.gatewayId);if(!e)throw new Xe(We.MissingPaymentMethod);s=this._getStrategy(e)}else s=this._strategyRegistryV2.get({id:Lm.NO_PAYMENT_DATA_REQUIRED});return s.execute(e,Object.assign(Object.assign({},t),{methodId:i.methodId,gatewayId:i.gatewayId})).then(()=>l(Fm.ExecuteSucceeded,void 0,r))})).pipe(ge(e=>Je(Fm.ExecuteFailed,e,r)))}}finalize(e){const{integrations:t}=null!=e?e:{};return i=>se(me(l(Fm.FinalizeRequested)),this._loadOrderPaymentsIfNeeded(i,e),de(()=>{return n=this,r=void 0,a=function*(){const n=i.getState(),{providerId:r="",gatewayId:o=""}=n.payment.getPaymentId()||{},a=n.paymentMethods.getPaymentMethod(r,o);if(!a)throw new xm;const s=this._registerIntegrations(n,a,t);let d;try{d=this._getStrategy(a)}catch(e){throw new xm}return yield d.finalize(Object.assign(Object.assign({},e),{methodId:a.id,gatewayId:a.gateway})),s&&this._errorLogger.log(s),l(Fm.FinalizeSucceeded,void 0,{methodId:a.id})},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())});var n,r,o,a})).pipe(ge(e=>{const t=i.getState().payment.getPaymentId();return Je(Fm.FinalizeFailed,e,{methodId:t&&t.providerId})}))}initialize(e){const{methodId:t,gatewayId:i,integrations:n}=e;return r=>de(()=>{const o=r.getState(),a=o.paymentMethods.getPaymentMethod(t,i);if(!a)throw new Xe(We.MissingPaymentMethod);if(t&&o.paymentStrategies.isInitialized({methodId:t,gatewayId:i}))return ce();const s=this._registerIntegrations(o,a,n);s&&this._errorLogger.log(s);const d=this._getStrategy(a).initialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:i}));return se(me(l(Fm.InitializeRequested,void 0,{methodId:t,gatewayId:i})),d.then(()=>l(Fm.InitializeSucceeded,void 0,{methodId:t,gatewayId:i})))}).pipe(ge(e=>Je(Fm.InitializeFailed,e,{methodId:t,gatewayId:i})))}deinitialize(e){const{methodId:t,gatewayId:i}=e;return n=>de(()=>{const r=n.getState(),o=r.paymentMethods.getPaymentMethod(t,i);if(!o)throw new Xe(We.MissingPaymentMethod);if(t&&!r.paymentStrategies.isInitialized({methodId:t,gatewayId:i}))return ce();const a=this._getStrategy(o).deinitialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:i}));return se(me(l(Fm.DeinitializeRequested,void 0,{methodId:t,gatewayId:i})),a.then(()=>l(Fm.DeinitializeSucceeded,void 0,{methodId:t,gatewayId:i})))}).pipe(ge(e=>Je(Fm.DeinitializeFailed,e,{methodId:t,gatewayId:i})))}widgetInteraction(e,t){return this._paymentStrategyWidgetActionCreator.widgetInteraction(e,t)}_registerIntegrations(e,t,i){const{features:n}=e.config.getStoreConfigOrThrow().checkoutSettings,r=Wt(n,"CHECKOUT-9450.lazy_load_payment_strategies",!1);let o=!0;try{this._strategyRegistry.getByMethod(t)}catch(e){o=!1}if(r&&!o){const e={id:t.id,gateway:t.gateway,type:t.type},n=Kt(this._strategyRegistryV2,null!=i?i:[],e,this._paymentIntegrationService);return Yt(this._strategyRegistryV2,null!=i?i:[],this._paymentIntegrationService),n}}_getStrategy(e){let t;try{t=this._strategyRegistry.getByMethod(e)}catch(i){t=this._strategyRegistryV2.get({id:e.id,gateway:e.gateway,type:e.type})}return t}_loadOrderPaymentsIfNeeded(e,t){const i=e.getState().checkout.getCheckout();return i&&i.orderId?this._orderActionCreator.loadOrderPayments(i.orderId,t):ce()}}class Um{isEqual(e,t){return A(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 qm extends Ze{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 Vm{constructor(e){this._checkoutRequestSender=e}validate(e,t){if(!e)throw new Xe(We.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then(t=>{const i=new Um;if(!(e.outstandingBalance===t.body.outstandingBalance&&this._compareCoupons(e.coupons,t.body.coupons)&&this._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&i.isEqual(e.cart,t.body.cart)))throw new qm(this._getComparableCheckout(e),this._getComparableCheckout(t.body))})}_compareCoupons(e,t){return A(B(e,"code"),B(t,"code"))}_compareGiftCertificates(e,t){return A(B(e,"code"),B(t,"code"))}_getComparableCheckout(e){const{cart:t,coupons:i,giftCertificates:n,outstandingBalance:r}=e;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:i,giftCertificates:n,outstandingBalance:r}}}class Gm{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 Hm extends Ze{constructor(){super("Please complete our human verification challenge and try again."),this.name="CardingProtectionChallengeNotCompletedError",this.type="carding_protection_challenge_not_completed"}}class $m extends Ze{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 Wm,Ym,Km=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Jm{constructor(e){this._googleRecaptcha=e}handle(e,t){return Km(this,void 0,void 0,function*(){return"string"==typeof e?this.handleWithRecaptchaSitekey(e,t):this.handleWithPaymentHumanVerificationRequestError(e)})}handleWithPaymentHumanVerificationRequestError(e){return Km(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 Km(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(be(1)).pipe(Ce(({error:e,token:t})=>Km(this,void 0,void 0,function*(){if(e instanceof oi)throw new Hm;if(e||!t)throw new $m;return{type:"recaptcha_v2_verification",data:{human_verification_token:t}}}))).toPromise()}_initialize(e){const t="cardingProtectionContainer";let i=document.getElementById(t);return i&&i.parentNode&&i.parentNode.removeChild(i),i=document.createElement("div"),i.setAttribute("id",t),document.body.appendChild(i),this._googleRecaptcha.load(t,e)}_isPaymentHumanVerificationRequest(e){const{additional_action_required:t,status:i}=e.body||{};return"additional_action_required"===i&&t&&"recaptcha_v2_verification"===t.type}}function Zm(e,t){const{body:i}=e,{errors:n=[]}=i;return new It(e,{message:Xm(n)||t,errors:n})}function Xm(e){if(Array.isArray(e))return e.reduce((e,t)=>t&&t.message?[...e,t.message]:e,[]).join(" ")}class Qm extends Ze{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 ey extends Ze{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 ty extends Ze{constructor(e){super(["Unable to proceed due to invalid user input values",...I(ne(e),e=>B(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"}(Wm||(Wm={})),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"}(Ym||(Ym={}));var iy=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ny{constructor(e,t,i,n,r,o,a,s,d,c){this._type=e,this._containerId=t,this._placeholder=i,this._accessibilityLabel=n,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.863.0&checkoutId=${this._checkoutId}`:"/checkout/payment/hosted-field?version=1.863.0";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 iy(this,void 0,void 0,function*(){const e=document.getElementById(this._containerId);if(!e)throw new Qm("Unable to proceed because the provided container ID is not valid.");e.appendChild(this._iframe),this._eventListener.listen();const t=ue(this._iframe,"load").pipe(Ce(({target:e})=>iy(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:Wm.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:Ym.AttachSucceeded,errorType:Ym.AttachFailed})})),be(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 iy(this,void 0,void 0,function*(){try{const i=this._eventPoster.post({type:Wm.SubmitRequested,payload:{fields:e,data:t}},{successType:Ym.SubmitSucceeded,errorType:Ym.SubmitFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],i)}catch(e){if(this._isSubmitErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new ey(e.payload.error.message);if(e.payload.response)throw Zm(e.payload.response);throw new Error(e.payload.error.message)}throw e}})}submitStoredCardForm(e,t){return iy(this,void 0,void 0,function*(){const i=this._eventPoster.post({type:Wm.StoredCardRequested,payload:{fields:e,data:t}},{successType:Ym.StoredCardSucceeded,errorType:Ym.StoredCardFailed});return this._detachmentObserver.ensurePresence([this._iframe],i)})}validateForm(){return iy(this,void 0,void 0,function*(){const e=this._eventPoster.post({type:Wm.ValidateRequested},{successType:Ym.Validated}),{payload:t}=yield this._detachmentObserver.ensurePresence([this._iframe],e);if(!t.isValid)throw new ty(t.errors)})}_getFontUrls(){const e="fonts.googleapis.com",t=document.querySelectorAll(`link[href*='${e}'][rel='stylesheet']`);return Array.prototype.slice.call(t).filter(t=>wi(t.href).hostname===e).filter(e=>ne(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===Ym.SubmitFailed}}var ry,oy=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ay{constructor(e,t,i,n,r){this._fields=e,this._eventListener=t,this._payloadTransformer=i,this._eventCallbacks=n,this._paymentHumanVerificationHandler=r,this._handleEnter=({payload:e})=>oy(this,void 0,void 0,function*(){try{yield this.validate()}catch(e){if(e instanceof Error&&"InvalidHostedFormValueError"!==e.name)throw e}const{onEnter:t=V}=this._eventCallbacks;t(e)});const{onBlur:o=V,onCardTypeChange:a=V,onFocus:s=V,onValidate:d=V}=this._eventCallbacks;this._eventListener.addListener(Ym.Blurred,({payload:e})=>o(e)),this._eventListener.addListener(Ym.CardTypeChanged,({payload:e})=>a(e)),this._eventListener.addListener(Ym.Focused,({payload:e})=>s(e)),this._eventListener.addListener(Ym.Validated,({payload:e})=>d(e)),this._eventListener.addListener(Ym.Entered,this._handleEnter),this._eventListener.addListener(Ym.CardTypeChanged,({payload:e})=>this._cardType=e.cardType),this._eventListener.addListener(Ym.BinChanged,({payload:e})=>this._bin=e.bin)}getBin(){return this._bin}getCardType(){return this._cardType}attach(){return oy(this,void 0,void 0,function*(){this._eventListener.listen();const e=this._getFirstField(),t=re(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 oy(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 i=yield this._paymentHumanVerificationHandler.handle(t);return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,i))}})}submitStoredCard(e){return oy(this,void 0,void 0,function*(){return this._getFirstField().submitStoredCardForm(e.fields,e.data)})}validate(){return oy(this,void 0,void 0,function*(){return this._getFirstField().validateForm()})}_getFirstField(){const e=this._fields[0];if(!e)throw new Qm("Unable to proceed because the payment form has no field defined.");return e}}function sy(e){return Boolean(e.instrumentId)}class dy{constructor(e){this._store=e}transform(e,t){const i=this._store.getState(),n=i.checkout.getCheckout(),r=i.config.getConfig(),o=i.instruments.getInstrumentsMeta(),a=i.order.getOrder(),s=i.order.getOrderMeta(),d=G(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv"),c=i.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),l=i.paymentMethods.getPaymentMethodsMeta(),u=o&&d&&sy(d)?`${i.payment.getPaymentToken()}, ${o.vaultAccessToken}`:i.payment.getPaymentToken();if(!u)throw new Xe(We.MissingPaymentToken);return{additionalAction:t,authToken:u,checkout:n,config:r,order:a,orderMeta:s,payment:d,paymentMethod:c,paymentMethodMeta:l}}}class cy{constructor(e){this._store=e}create(e,t,i){const n=Object.keys(t.fields).reduce((n,r)=>{const o=t.fields[r];return o?[...n,new ny(r,o.containerId,o.placeholder||"",o.accessibilityLabel||"",t.styles||{},new Ci(e),new $i(e),new Ai(new hi),i,"instrumentId"in o?this._getCardInstrument(o.instrumentId):void 0)]:n},[]);return new ay(n,new $i(e),new dy(this._store),W(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new Jm(vi(o())))}_getCardInstrument(e){const{instruments:{getCardInstrument:t}}=this._store.getState(),i=t(e);if(!i)throw new Xe(We.MissingPaymentInstrument);return i}}!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"}(ry||(ry={}));class ly{constructor(e,t,i,n){this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=i,this._paymentHumanVerificationHandler=n,this.initializeOffsitePayment=({methodId:e,gatewayId:t,instrumentId:i,target:n,promise:r,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})=>s=>{let d;i?d={formattedPayload:{bigpay_token:i}}: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 se(me(l(ry.InitializeOffsitePaymentRequested)),Promise.race([this._paymentRequestSender.initializeOffsitePayment(c,n),r].filter(Boolean)).then(()=>l(ry.InitializeOffsitePaymentSucceeded))).pipe(ge(e=>Je(ry.InitializeOffsitePaymentFailed,e)))}}submitPayment(e){return t=>se(me(l(ry.SubmitPaymentRequested)),de(()=>{return i=this,n=void 0,o=function*(){try{return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,t.getState()))}catch(i){const n=yield this._paymentHumanVerificationHandler.handle(i);return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(Object.assign(Object.assign({},e),{additionalAction:n}),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}).pipe(Ce(({body:e})=>se(this._orderActionCreator.loadCurrentOrder()(t),me(l(ry.SubmitPaymentSucceeded,e)))))).pipe(ge(e=>Je(ry.SubmitPaymentFailed,e)))}}class uy{constructor(e){this._client=e}submitPayment(e){return new Promise((t,i)=>{this._client.submitPayment(e,(e,n)=>{e?i(this._transformResponse(e)):t(this._transformResponse(n))})})}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 hy(e,t){let i;return function(e){return void 0!==e.id}(e)?i=e.id:t&&t.length&&(i=t[0].id),{id:i,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 py=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function my(e){return{code:e.code,discount:e.displayName,discountType:py.indexOf(e.couponType)}}function yy(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function gy(e){const t=[];return(e||[]).forEach(e=>{(e.banners||[]).forEach(e=>{t.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})})}),t}function vy(e,t,i="id"){return Object.keys(e).reduce((n,r)=>[...n,...e[r].map(e=>"giftCertificates"===r?function(e,t){const i=new id(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:i.toInteger(e.amount),integerAmountAfterDiscount:i.toInteger(e.amount),integerUnitPrice:i.toInteger(e.amount),integerUnitPriceAfterDiscount:i.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,i,n="id"){const r=new id(i);return{id:e[n],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,i))],[])}function fy(e){const t=e.cart.currency.decimalPlaces,i=new id(t);return{id:e.cart.id,items:vy(e.cart.lineItems,t),currency:e.cart.currency.code,coupon:{discountedAmount:K(e.cart.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.cart.coupons.map(my)},discount:{amount:e.cart.discountAmount,integerAmount:i.toInteger(e.cart.discountAmount)},discountNotifications:gy(e.promotions),giftCertificate:{totalDiscountedAmount:K(e.giftCertificates,(e,t)=>e+t.used,0),appliedGiftCertificates:F(e.giftCertificates.map(yy),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount),required:Z(e.cart.lineItems.physicalItems,e=>e.isShippingRequired)},subtotal:{amount:e.subtotal,integerAmount:i.toInteger(e.subtotal)},storeCredit:{amount:e.customer?e.customer.storeCredit:0},taxSubtotal:{amount:e.taxTotal,integerAmount:i.toInteger(e.taxTotal)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:i.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:i.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.grandTotal,integerAmount:i.toInteger(e.grandTotal)}}}var Sy;!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"}(Sy||(Sy={}));const wy=Sy;function Iy(e,t){const i=e.firstName||t.firstName||"",n=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map(e=>hy(e)),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:i,lastName:n,name:e.fullName||[i,n].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}class _y{format(e){const[t="",i=""]=e.split(new RegExp("\\s*/\\s*")),n=t.slice(0,2),r=4===i.length?i.slice(-2):i?i.slice(0,2):t.slice(2);return e.length<2?t:e.length>3&&!r?n:`${n} / ${r}`}toObject(e){const[t="",i=""]=e.split(new RegExp("\\s*/\\s*"));return/^\d+$/.test(t)&&/^\d+$/.test(i)?{month:1===t.length?`0${t}`:t.slice(0,2),year:2===i.length?`20${i}`:i.slice(0,4)}:{month:"",year:""}}}class Cy{format(e){const{card:t}=Me(e);if(!t)return e;const i=j(De(e).map(e=>j(e.lengths))),n=this.unformat(e).slice(0,i);return t.gaps.filter(e=>n.length>e).reduce((e,t,i)=>[e.slice(0,t+i),e.slice(t+i)].join(" "),n)}unformat(e){const{card:t}=Me(e);return t?e.replace(new RegExp(" ","g"),""):e}}function by(e,t={}){const i=e.currency.decimalPlaces,n=new id(i);return{id:e.orderId,items:vy(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:Ey(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:n.toInteger(e.baseAmount)},coupon:{discountedAmount:K(e.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.coupons.map(my)},discount:{amount:e.discountAmount,integerAmount:n.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:Oy(e.payments),socialData:Ty(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:n.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:n.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:Py(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:n.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function Py(e){const t=S(e,{providerId:"storecredit"});return t?t.amount:0}function Oy(e){const t=f(e,{providerId:"giftcertificate"});return{totalDiscountedAmount:K(t,(e,t)=>t.amount+e,0),appliedGiftCertificates:F(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 Ey(e,t={}){const i=S(e,Ay);return i?{id:i.providerId,status:(n=i.detail.step,`PAYMENT_STATUS_${n}`),helpText:i.detail.instructions,returnUrl:t.returnUrl}:{};var n}function Ay(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function Ty(e){const t={};return[...e.lineItems.physicalItems,...e.lineItems.digitalItems].forEach(e=>{var i;t[e.id]=(i=e,["fb","tw","gp"].reduce((e,t)=>{const n=i.socialMedia&&S(i.socialMedia,e=>e.code===t);return n?(e[t]={name:i.name,description:i.name,image:i.imageUrl,url:n.link,shareText:n.text,sharingLink:n.link,channelName:n.channel,channelCode:n.code},e):e},{}))}),t}function ky(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 Dy{constructor(){this._cardExpiryFormatter=new _y,this._cardNumberFormatter=new Cy}transform(e,t){const i=t.billingAddress.getBillingAddress(),n=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&&i&&Iy(r,i),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 Xe(We.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:g,customer:y,billingAddress:i&&hy(i),shippingAddress:s&&hy(s,d),shippingOption:c&&ky(c,!0),cart:n&&fy(n),order:o&&by(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:W(l&&l.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}transformWithHostedFormData(e,t,i){const{additionalAction:n,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:n,authToken:r,paymentMethod:l&&this._transformPaymentMethod(l),customer:s&&s.billingAddress&&o&&Iy(o.customer,s.billingAddress),billingAddress:s&&s.billingAddress&&hy(s.billingAddress),shippingAddress:p&&o&&hy(p,o.consignments),shippingOption:m&&ky(m,!0),cart:o&&fy(o),order:s&&by(s,d),orderMeta:d,payment:this._transformHostedInputValues(e,c,i),quoteMeta:{request:Object.assign(Object.assign({},u),{geoCountryCode:a&&a.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:a&&W(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}):e.id===wy.BRAINTREE_VENMO?Object.assign(Object.assign({},e),{id:wy.BRAINTREE_PAYPAL}):e:Object.assign(Object.assign({},e),{gateway:e.id})}_transformHostedInputValues(e,t,i){return"instrumentId"in t?Object.assign(Object.assign({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:i}):Object.assign(Object.assign({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:i})}_mapShippingAddress(e,t){var i,n,r,o;if(t){const a=null===(n=null===(i=t.initializationData)||void 0===i?void 0:i.bopis)||void 0===n?void 0:n.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 My=e=>{const{type:t,initializationStrategy:i}=e;return t===Lm.PPSDK&&"string"==typeof(null==i?void 0:i.type)};class zy extends Bt{getByMethod(e){if(!e)return this.get();const t=this._getToken(e),i=[e.gateway,e.id].filter(e=>null!=e).join("-");return this.get(t,i)}_getToken(e){if(My(e))return Lm.PPSDK;if("klarna"===e.gateway)return Lm.KLARNAV2;const t=e.gateway||e.id;if(this._hasFactoryForMethod(t))return t;if("PAYMENT_TYPE_OFFLINE"===e.type)return Lm.OFFLINE;throw new Lt(`'${t}' is not registered.`)}_hasFactoryForMethod(e){return this._hasFactory(e)}}const Ny="FINALIZE";class xy extends Lt{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 Fy=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i};class Ry{constructor(e,t,i,n){this._store=e,this._orderActionCreator=t,this._paymentActionCreator=i,this._hostedFormFactory=n}execute(e,t){var i,n;return this._isHostedPaymentFormEnabled(null===(i=e.payment)||void 0===i?void 0:i.methodId,null===(n=e.payment)||void 0===n?void 0:n.gatewayId)&&this._shouldRenderHostedForm?this._executeWithHostedForm(e,t):this._executeWithoutHostedForm(e,t)}finalize(e){return Promise.reject(new xm)}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:i}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:n=""}={}}=i.getStoreConfig()||{};if(!t)throw new Lt;const r=this._hostedFormFactory.create(n,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:i}=e,n=Fy(e,["payment"]),r=i&&i.paymentData;if(!i||!r)throw new xy(["payment.paymentData"]);return this._store.dispatch(this._orderActionCreator.submitOrder(n,t)).then(()=>this._store.dispatch(this._paymentActionCreator.submitPayment(Object.assign(Object.assign({},i),{paymentData:r}))))}_executeWithHostedForm(e,t){const{payment:i}=e,n=Fy(e,["payment"]),r=this._hostedForm;if(!r)throw new pi(si.PaymentNotInitialized);if(!i||!i.methodId)throw new xy(["payment.methodId"]);return r.validate().then(()=>this._store.dispatch(this._orderActionCreator.submitOrder(n,t))).then(()=>r.submit(i)).then(()=>this._store.dispatch(this._orderActionCreator.loadCurrentOrder()))}_isHostedPaymentFormEnabled(e,t){if(!e)return!1;const{paymentMethods:{getPaymentMethodOrThrow:i}}=this._store.getState();return!0===i(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!ne(e&&e.creditCard&&e.creditCard.form.fields).every(k)}}class Ly extends Ry{constructor(e,t,i,n,r){super(e,t,i,n),this._formPoster=r}execute(e,t){return super.execute(e,t).catch(e=>e instanceof It&&Z(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(),i=t.order.getOrder();return i&&t.payment.getPaymentStatus()===Ny?this._store.dispatch(this._orderActionCreator.finalizeOrder(i.orderId,e)):Promise.reject(new xm)}}class By extends Ze{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}const jy="redirecting";class Uy{constructor(){this._isRedirecting=this.currentUrlHasRedirectingParam()}isRedirecting(){return this._isRedirecting}setRedirecting(e){e?this.setRedirectingParamOnUrl():this.removeRedirectingParamFromUrl(),this._isRedirecting=e}currentUrlHasRedirectingParam(){return jy in this.getCurrentUrl().query}getCurrentUrl(){return Ne(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),{[jy]:"true"})});this.replaceCurrentUrl(xe(t))}removeRedirectingParamFromUrl(){this.currentUrlHasRedirectingParam()&&this.replaceCurrentUrl(ze(window.location.href,[jy]))}}const qy=$([e=>"continue"===C(e,"type")&&"redirect"===C(e,"code")&&(e=>{const t=C(e,"form_fields");return z(C(e,"url"))&&(N(t)||D(t))})(C(e,"parameters")),e=>"continue"===C(e,"type")&&"resubmit_with_human_verification"===C(e,"code")&&(e=>{const t=C(e,"available_methods");return O(t)})(C(e,"parameters"))]);class Vy{constructor(e,t){this._formPoster=e,this._humanVerificationHandler=t}handle(e,t){switch(e.code){case"redirect":return(({url:e,form_fields:t},i)=>{const n=new Uy;return n.isRedirecting()?(n.setRedirecting(!1),Promise.reject(new By)):(n.setRedirecting(!0),t?i.postForm(e,t):window.location.assign(e),new Promise(V))})(e.parameters,this._formPoster);case"resubmit_with_human_verification":return(({available_methods:e},t,i)=>{return n=void 0,r=void 0,a=function*(){if(!i)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:n,parameters:r}=e[0],o=yield t.handle(n,r.key);return i(o)},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())});var n,r,o,a})(e.parameters,this._humanVerificationHandler,null==t?void 0:t.humanVerification)}}}class Gy{constructor(e){this._continueHandler=e}handle(e,t){const{body:i}=e;return(e=>"success"===C(e,"type"))(i)?Promise.resolve():(e=>qy(e))(i)?this._continueHandler.handle(i,null==t?void 0:t.continue):(e=>"failure"===C(e.body,"type")&&z(C(e.body,"code")))(e)?(e=>{return Promise.reject(new It((t=e,Object.assign(Object.assign({},t),{body:{errors:[{code:t.body.code}]}}))));var t})(e):((e=>{C(e.body,"type")})(e),(e=>Promise.reject(new It(e)))(e))}}const Hy="completed-payments";class $y{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(Hy)||[]}setCompletedPayments(e){this._browserStorage.setItem(Hy,e)}}var Wy,Yy=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ky{constructor(e,t,i,n,r){this._store=e,this._orderActionCreator=t,this._subStrategyRegistry=i,this._paymentResumer=n,this._completedPayments=new $y(r)}execute(e,t){var i;return Yy(this,void 0,void 0,function*(){const{bigpayBaseUrl:n}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==t?void 0:t.methodId))throw new Lt('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:r}=t,{payment:o}=e,a=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{_subStrategy:s}=this;if(!s)throw new pi(si.PaymentNotInitialized);yield this._store.dispatch(this._orderActionCreator.submitOrder(a,t));const d=null===(i=this._store.getState().order.getOrderMeta())||void 0===i?void 0:i.token;if(!d)throw new Xe(We.MissingOrder);return yield s.execute({methodId:r,payment:o,bigpayBaseUrl:n,token:d}),this._store.getState()})}finalize(e){return Yy(this,void 0,void 0,function*(){const t=this._store.getState().order.getOrderOrThrow();if(t.isComplete)return this._store.getState();const{bigpayBaseUrl:i}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==e?void 0:e.methodId))throw new Lt('Unable to submit payment because "options.methodId" argument is not provided.');const n=this._store.getState().order.getPaymentId(e.methodId);if(!n||!t||this._completedPayments.isCompleted(n))throw new xm;const{orderId:r}=t;return yield this._paymentResumer.resume({paymentId:n,bigpayBaseUrl:i,orderId:r}).catch(e=>{throw this._completedPayments.setCompleted(n),e}),this._store.getState()})}initialize(e){return Yy(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new Lt('Unable to submit payment because "options.methodId" argument is not provided.');const t=((e,t)=>{const i=e.getState().paymentMethods.getPaymentMethod(t);if(i&&My(i))return i})(this._store,e.methodId);if(!t)throw new pi(si.PaymentNotInitialized);if(this._subStrategy=this._subStrategyRegistry.getByMethod(t),!this._subStrategy)throw new pi(si.PaymentNotInitialized);return yield this._subStrategy.initialize(e),this._store.getState()})}deinitialize(e){var t;return Yy(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"}(Wy||(Wy={}));const Jy=m([[e=>"card_ui"===e.type,y(Wy.CARD)],[e=>"none"===e.type,y(Wy.NONE)],[X,y(Wy.UNSUPPORTED)]]);class Zy extends Bt{getByMethod(e){const t=Jy(e.initializationStrategy);return this.get(t)}}var Xy=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Qy{constructor(e,t,i,n){this._store=e,this._orderActionCreator=t,this._hostedFormFactory=i,this._ppsdkStepHandler=n}execute(e){return Xy(this,void 0,void 0,function*(){const t=this._hostedForm;if(!t)throw new pi(si.PaymentNotInitialized);const{additionalAction:i,payment:n}=e;if(!n||!n.methodId)throw new xy(["payment.methodId"]);yield t.validate();const{payload:r}=yield t.submit(n,i),{response:o}=r;yield this._ppsdkStepHandler.handle(o,{continue:{humanVerification:t=>Xy(this,void 0,void 0,function*(){return this.execute(Object.assign({additionalAction:t},e))})}}),yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder())})}initialize(e){return Xy(this,void 0,void 0,function*(){const t=e&&e.creditCard&&e.creditCard.form,{config:i,checkout:n}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:r=""}={}}=i.getStoreConfig()||{},o=n.getCheckoutOrThrow().id;if(!t)throw new Lt;const a=t&&this._hostedFormFactory.create(r,t,o);yield a.attach(),this._hostedForm=a})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}class eg{constructor(e,t){this._requestSender=e,this._stepHandler=t}execute({methodId:e,bigpayBaseUrl:t,token:i}){const n={credentials:!1,body:{payment_method_id:e},headers:{authorization:i,"X-XSRF-TOKEN":null}};return this._requestSender.post(`${t}/payments`,n).then(e=>this._stepHandler.handle(e))}initialize(){return Promise.resolve()}deinitialize(){}}var tg,ig,ng=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class rg{constructor(e,t){this._requestSender=e,this._stepHandler=t}resume({paymentId:e,bigpayBaseUrl:t,orderId:i}){return ng(this,void 0,void 0,function*(){const n={credentials:!1,headers:{authorization:yield this._getToken(i).catch(()=>{throw new xm}),"X-XSRF-TOKEN":null}};return this._requestSender.get(`${t}/payments/${e}`,n).then(e=>this._stepHandler.handle(e))})}_getToken(e){return ng(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 og extends Ry{constructor(e,t,i,n,r){super(e,t,i,n),this._wepayRiskClient=r}initialize(e){return this._wepayRiskClient.initialize(),super.initialize(e)}execute(e,t){const i=this._wepayRiskClient.getRiskToken(),n=q({},e,{payment:{paymentData:{deviceSessionId:i}}});return super.execute(n,t)}}class ag{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 pi(si.PaymentNotInitialized);return this._riskClient.generate_risk_token(),this._riskClient.get_risk_token()}}class sg{constructor(e){this._requestSender=e}createBuyNowCart(e,{timeout:t}={}){const i=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post("/api/storefront/carts",{body:e,headers:i,timeout:t})}}!function(e){e.UpdatePaymentProviderCustomer="UPDATE_PAYMENT_PROVIDER_CUSTOMER"}(tg||(tg={}));class dg{updatePaymentProviderCustomer(e){return me(l(tg.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"}(ig||(ig={}));var cg;class lg{constructor(e,t){this._remoteCheckoutRequestSender=e,this._checkoutActionCreator=t}initializeBilling(e,t,i){return oe.create(n=>{n.next(l(ig.InitializeRemoteBillingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeBilling(e,t,i).then(({body:t={}})=>{n.next(l(ig.InitializeRemoteBillingSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(ig.InitializeRemoteBillingFailed,t,{methodId:e}))})})}initializeShipping(e,t,i){return oe.create(n=>{n.next(l(ig.InitializeRemoteShippingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeShipping(e,t,i).then(({body:t={}})=>{n.next(l(ig.InitializeRemoteShippingSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(ig.InitializeRemoteShippingFailed,t,{methodId:e}))})})}initializePayment(e,t,i){return oe.create(n=>{n.next(l(ig.InitializeRemotePaymentRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializePayment(e,t,i).then(({body:t={}})=>{n.next(l(ig.InitializeRemotePaymentSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(ig.InitializeRemotePaymentFailed,t,{methodId:e}))})})}loadSettings(e,t){return oe.create(i=>{i.next(l(ig.LoadRemoteSettingsRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.loadSettings(e,t).then(({body:t})=>{i.next(l(ig.LoadRemoteSettingsSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(ig.LoadRemoteSettingsFailed,t,{methodId:e}))})})}signOut(e,t){return oe.create(i=>{i.next(l(ig.SignOutRemoteCustomerRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.signOut(e,t).then(()=>{i.next(l(ig.SignOutRemoteCustomerSucceeded,void 0,{methodId:e})),i.complete()}).catch(t=>{i.error(h(ig.SignOutRemoteCustomerFailed,t,{methodId:e}))})})}forgetCheckout(e,t){return se(me(l(ig.ForgetCheckoutRemoteCustomerRequested,void 0,{methodId:e})),de(()=>{return i=this,n=void 0,o=function*(){return yield this._remoteCheckoutRequestSender.forgetCheckout(t),yield this._checkoutActionCreator.loadCurrentCheckout(),l(ig.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).pipe(ge(t=>Je(ig.ForgetCheckoutRemoteCustomerFailed,t,{methodId:e})))}updateCheckout(e,t){return l(ig.UpdateRemoteCheckout,t,{methodId:e})}}class ug{constructor(e){this._requestSender=e}initializeBilling(e,t,{timeout:i}={}){const n=`/remote-checkout/${e}/billing`;return this._requestSender.get(n,{params:t,timeout:i,headers:rt})}initializeShipping(e,t,{timeout:i}={}){const n=`/remote-checkout/${e}/shipping`;return this._requestSender.get(n,{params:t,timeout:i,headers:rt})}initializePayment(e,t,{timeout:i}={}){const n=`/remote-checkout/${e}/payment`;return this._requestSender.get(n,{params:t,timeout:i,headers:rt})}loadSettings(e,{timeout:t}={}){const i=`/remote-checkout/${e}/settings`;return this._requestSender.get(i,{timeout:t,headers:rt})}signOut(e,{timeout:t}={}){const i=`/remote-checkout/${e}/signout`;return this._requestSender.get(i,{timeout:t,headers:rt})}generateToken({timeout:e}={}){return this._requestSender.get("/remote-checkout-token",{timeout:e,headers:rt})}trackAuthorizationEvent({timeout:e}={}){return this._requestSender.post("/remote-checkout/events/shopper-checkout-service-provider-authorization-requested",{timeout:e,headers:rt})}forgetCheckout({timeout:e}={}){return this._requestSender.post("/remote-checkout/forget-checkout",{timeout:e,headers:rt})}}!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"}(cg||(cg={}));class hg{constructor(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}unassignItemsByAddress(e,t){return i=>{const n=i.getState();if(!n.checkout.getCheckout())throw new Xe(We.MissingCheckout);const r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=n.consignments.getConsignmentByAddress(r);if(!o)throw new Lt("No consignment found for the specified address");const a=this._removeLineItems(e.lineItems,o,n.cart.getCart());return a.length?this.updateConsignment({id:o.id,address:r,lineItems:a},t)(i):this.deleteConsignment(o.id,t)(i)}}assignItemsByAddress(e,t){return i=>{const n=i.getState(),r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=n.consignments.getConsignmentByAddress(r);return this._createOrUpdateConsignment({id:o&&o.id,address:r,lineItems:this._addLineItems(e.lineItems,o,n.cart.getCart())},t)(i)}}selectShippingOption(e,t){return i=>oe.create(n=>{const r=i.getState(),o=r.checkout.getCheckout(),a=r.consignments.getConsignments();if(!o)throw new Xe(We.MissingCheckout);if(!a||!a.length)throw new Xe(We.MissingConsignments);const s={id:a[0].id,shippingOptionId:e},d={id:a[0].id};n.next(l(cg.UpdateShippingOptionRequested,void 0,d)),this._consignmentRequestSender.updateConsignment(o.id,s,t).then(({body:e})=>{n.next(l(cg.UpdateShippingOptionSucceeded,e,d)),n.complete()}).catch(e=>{n.error(h(cg.UpdateShippingOptionFailed,e,d))})})}loadShippingOptions(e){return t=>oe.create(i=>{const n=t.getState().checkout.getCheckout();if(!n)throw new Xe(We.MissingCheckout);i.next(l(cg.LoadShippingOptionsRequested)),this._checkoutRequestSender.loadCheckout(n.id,Object.assign(Object.assign({},e),{params:{include:[At.AvailableShippingOptions]}})).then(({body:e})=>{i.next(l(cg.LoadShippingOptionsSucceeded,e)),i.complete()}).catch(e=>{i.error(h(cg.LoadShippingOptionsFailed,e))})})}updateAddress(e,t){return i=>{const n=this._getUpdateAddressRequestBody(e,i),r=i.getState().consignments.getConsignments();return r&&r.length&&(n.id=r[0].id),this._createOrUpdateConsignment(n,t)(i)}}createConsignments(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r||!r.id)throw new Xe(We.MissingCheckout);n.next(l(cg.CreateConsignmentsRequested)),this._consignmentRequestSender.createConsignments(r.id,e,t).then(({body:e})=>{n.next(l(cg.CreateConsignmentsSucceeded,e)),n.complete()}).catch(e=>{n.error(h(cg.CreateConsignmentsFailed,e))})})}updateConsignment(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r||!r.id)throw new Xe(We.MissingCheckout);const o={id:e.id};n.next(l(cg.UpdateConsignmentRequested,void 0,o)),this._consignmentRequestSender.updateConsignment(r.id,e,t).then(({body:e})=>{n.next(l(cg.UpdateConsignmentSucceeded,e,o)),n.complete()}).catch(e=>{n.error(h(cg.UpdateConsignmentFailed,e,o))})})}deleteConsignment(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout(),o={id:e};if(!r||!r.id)throw new Xe(We.MissingCheckout);n.next(l(cg.DeleteConsignmentRequested,void 0,o)),this._consignmentRequestSender.deleteConsignment(r.id,e,t).then(({body:e})=>{n.next(l(cg.DeleteConsignmentSucceeded,e,o)),n.complete()}).catch(e=>{n.error(h(cg.DeleteConsignmentFailed,e,o))})})}updateShippingOption(e,t){return i=>oe.create(n=>{var r;const o=i.getState().checkout.getCheckout(),a=i.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 n.complete();if(!o||!o.id)throw new Xe(We.MissingCheckout);const s={id:e.id};n.next(l(cg.UpdateShippingOptionRequested,void 0,s)),this._consignmentRequestSender.updateConsignment(o.id,e,t).then(({body:e})=>{n.next(l(cg.UpdateShippingOptionSucceeded,e,s)),n.complete()}).catch(e=>{n.error(h(cg.UpdateShippingOptionFailed,e,s))})})}_createOrUpdateConsignment(e,t){return i=>{const n=i.getState().checkout.getCheckout();if(!n||!n.id)throw new Xe(We.MissingCheckout);return this._isUpdateConsignmentRequest(e)?this.updateConsignment(e,t)(i):this.createConsignments([e],t)(i)}}_getUpdateAddressRequestBody(e,t){const i=t.getState().cart.getCart();if(!i)throw new Xe(We.MissingCart);const{physicalItems:n,customItems:r=[]}=i.lineItems;return{address:e,lineItems:[...n,...r].map(e=>({itemId:e.id,quantity:e.quantity}))}}_removeLineItems(e,t,i){if(!i)throw new Xe(We.MissingCart);return this._hydrateLineItems(t.lineItemIds,i).map(t=>{const i=S(e,e=>e.itemId===t.itemId);return Object.assign(Object.assign({},t),{quantity:i?t.quantity-i.quantity:t.quantity})}).filter(e=>e.quantity>0)}_addLineItems(e,t,i){if(!t)return e;if(!i)throw new Xe(We.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,i)).filter(e=>e.quantity>0)}_hydrateLineItems(e,t){return e.map(e=>{const i=S(t.lineItems.physicalItems,t=>t.id===e);return{itemId:e,quantity:i?i.quantity:0}})}_isUpdateConsignmentRequest(e){return!!e.id}_consignmentHasAddress(e){return"object"==typeof e&&"address"in e}}const pg=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"];class mg{constructor(e){this._requestSender=e}createConsignments(e,t,{timeout:i,params:{include:n}={}}={}){const r=`/api/storefront/checkouts/${e}/consignments`,o=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(r,{body:t,params:{include:Xt(pg,n)},headers:o,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}updateConsignment(e,t,{timeout:i,params:{include:n}={}}={}){const{id:r}=t,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(t,["id"]),a=`/api/storefront/checkouts/${e}/consignments/${r}`,s=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.put(a,{body:o,params:{include:Xt(pg,n)},headers:s,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}deleteConsignment(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/consignments/${t}`,r=Object.assign({Accept:nt.JsonV1},rt),o=Mt(pg);return this._requestSender.delete(n,{params:{include:o},headers:r,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}}var yg,gg;!function(e){e.LoadShippingCountriesRequested="LOAD_SHIPPING_COUNTRIES_REQUESTED",e.LoadShippingCountriesSucceeded="LOAD_SHIPPING_COUNTRIES_SUCCEEDED",e.LoadShippingCountriesFailed="LOAD_SHIPPING_COUNTRIES_FAILED"}(yg||(yg={}));class vg{constructor(e,t){this._shippingCountryRequestSender=e,this._store=t}loadCountries(e){const{checkout:t}=this._store.getState(),i=t.getCheckout(),n=i?i.channelId:null;return oe.create(t=>{t.next(l(yg.LoadShippingCountriesRequested)),this._shippingCountryRequestSender.loadCountries(n,e).then(e=>{t.next(l(yg.LoadShippingCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(yg.LoadShippingCountriesFailed,e))})})}}class fg{constructor(e,t){this._requestSender=e,this._config=t}loadCountries(e,{timeout:t}={}){const i="/internalapi/v1/shipping/countries"+(e?`?channel_id=${e}`:""),n=Object.assign({"Accept-Language":this._config.locale},rt);return this._requestSender.get(i,{headers:n,timeout:t})}}!function(e){e.ApplyStoreCreditRequested="APPLY_STORE_CREDIT_REQUESTED",e.ApplyStoreCreditSucceeded="APPLY_STORE_CREDIT_SUCCEEDED",e.ApplyStoreCreditFailed="APPLY_STORE_CREDIT_FAILED"}(gg||(gg={}));var Sg;class wg{constructor(e){this._storeCreditRequestSender=e}applyStoreCredit(e,t){return i=>se(me(l(gg.ApplyStoreCreditRequested)),de(()=>{return n=this,r=void 0,a=function*(){const n=i.getState().checkout.getCheckout();if(!n)throw new Xe(We.MissingCheckout);const{body:r}=yield e?this._storeCreditRequestSender.applyStoreCredit(n.id,t):this._storeCreditRequestSender.removeStoreCredit(n.id,t);return l(gg.ApplyStoreCreditSucceeded,r)},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())});var n,r,o,a})).pipe(ge(e=>Je(gg.ApplyStoreCreditFailed,e)))}}class Ig{constructor(e){this._requestSender=e}applyStoreCredit(e,{timeout:t}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,n=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(i,{headers:n,timeout:t,params:{include:Mt(Et)}})}removeStoreCredit(e,{timeout:t}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,n=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.delete(i,{headers:n,timeout:t,params:{include:Mt(Et)}})}}!function(e){e.UpdateSubscriptionsRequested="UPDATE_SUBSCRIPTIONS_REQUESTED",e.UpdateSubscriptionsSucceeded="UPDATE_SUBSCRIPTIONS_SUCCEEDED",e.UpdateSubscriptionsFailed="UPDATE_SUBSCRIPTIONS_FAILED"}(Sg||(Sg={}));class _g extends It{constructor(e){super(e),this.name="UpdateSubscriptionsError",this.type="update_subscriptions"}}class Cg{constructor(e){this._subscriptionsRequestSender=e}updateSubscriptions(e,t){return se(me(l(Sg.UpdateSubscriptionsRequested)),de(()=>{return i=this,n=void 0,o=function*(){const{body:i}=yield this._subscriptionsRequestSender.updateSubscriptions(e,t);return l(Sg.UpdateSubscriptionsSucceeded,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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).pipe(ge(e=>Je(Sg.UpdateSubscriptionsFailed,new _g(e))))}}class bg{constructor(e){this._requestSender=e}updateSubscriptions(e,{timeout:t}={}){const i=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:i,timeout:t})}}function Pg(e){return M(e)}const Og=U(e=>Array.isArray(e)?e.map(e=>Eg(e)):Pg(e)?Object.keys(e).reduce((t,i)=>Object.assign(Object.assign({},t),{[i]:Eg(e[i])}),{}):e);Og.cache=new WeakMap;const Eg=e=>"object"==typeof e&&null!==e?Og(e):e;function Ag(e){return(...t)=>Eg(e(...t))}function Tg({billingAddress:{getBillingAddress:e,getBillingAddressOrThrow:t},cart:{getCart:i,getCartOrThrow:n,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:v,getCustomerOrThrow:f},instruments:{getCardInstrument:S,getCardInstrumentOrThrow:w,getInstruments:I,getInstrumentsMeta:_},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:N},paymentMethods:{getPaymentMethod:x,getPaymentMethodOrThrow:F,getPaymentMethodsMeta:R},paymentProviderCustomer:{getPaymentProviderCustomer:L,getPaymentProviderCustomerOrThrow:B},paymentStrategies:{isInitialized:j},shippingAddress:{getShippingAddress:U,getShippingAddressOrThrow:q,getShippingAddresses:V,getShippingAddressesOrThrow:G},shippingCountries:{getShippingCountries:H}}){return{getHost:Ag(c),getLocale:Ag(l),getCartLocale:Ag(r),getBillingAddress:Ag(e),getBillingAddressOrThrow:Ag(t),getCart:Ag(i),getCartOrThrow:Ag(n),getCheckout:Ag(o),getCheckoutOrThrow:Ag(a),getCountries:Ag(g),getStoreConfig:Ag(u),getStoreConfigOrThrow:Ag(h),getConfig:Ag(p),getConsignments:Ag(m),getConsignmentsOrThrow:Ag(y),getContextConfig:Ag(d),getCustomer:Ag(v),getCustomerOrThrow:Ag(f),getCardInstrument:Ag(S),getInstruments:Ag(I),getCardInstrumentOrThrow:Ag(w),getOrder:Ag(C),getOrderOrThrow:Ag(b),getOrderMeta:Ag(P),getInstrumentsMeta:Ag(_),getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,getPaymentMethod:Ag(x),getPaymentMethodOrThrow:Ag(F),getPaymentMethodsMeta:Ag(R),getPaymentProviderCustomer:Ag(L),getPaymentProviderCustomerOrThrow:Ag(B),getShippingAddress:Ag(U),getShippingAddressOrThrow:Ag(q),getShippingAddresses:Ag(V),getShippingAddressesOrThrow:Ag(G),getShippingCountries:Ag(H),getOutstandingBalance:Ag(s),isPaymentDataRequired:N,isPaymentMethodInitialized:j}}var kg,Dg=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Mg{constructor(e,t,i,n,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S){this._store=e,this._storeProjectionFactory=t,this._checkoutActionCreator=i,this._checkoutValidator=n,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=v,this._remoteCheckoutActionCreator=f,this._paymentStrategyWidgetActionCreator=S,this._storeProjection=this._storeProjectionFactory.create(this._store)}createHostedForm(e,t){const i=this._storeProjection.getState().getCheckoutOrThrow().id;return this._hostedFormFactory.create(e,t,i)}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}getState(){return this._storeProjection.getState()}initializeOffsitePayment(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.initializeOffsitePayment(e)),this._storeProjection.getState()})}loadCheckout(e){return Dg(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 Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()),this._storeProjection.getState()})}loadPaymentMethod(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e,t)),this._storeProjection.getState()})}loadPaymentMethods(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods(e)),this._storeProjection.getState()})}submitOrder(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.submitOrder(e,t)),this._storeProjection.getState()})}submitPayment(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.submitPayment(e)),this._storeProjection.getState()})}finalizeOrder(e){return Dg(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 Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(e)),this._storeProjection.getState()})}updateShippingAddress(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.updateAddress(e)),this._storeProjection.getState()})}selectShippingOption(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t)),this._storeProjection.getState()})}signInCustomer(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signInCustomer(e,t)),this._storeProjection.getState()})}signOutCustomer(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signOutCustomer(e)),this._storeProjection.getState()})}createBuyNowCart(e,t){return Dg(this,void 0,void 0,function*(){const{body:i}=yield this._cartRequestSender.createBuyNowCart(e,t);return i})}applyStoreCredit(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(e,t)),this._storeProjection.getState()})}applyCoupon(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.applyCoupon(e,t)),this._storeProjection.getState()})}removeCoupon(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.removeCoupon(e,t)),this._storeProjection.getState()})}verifyCheckoutSpamProtection(){return Dg(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 Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder(e)),this._storeProjection.getState()})}updatePaymentProviderCustomer(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(e)),this._storeProjection.getState()})}loadShippingCountries(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._shippingCountryActionCreator.loadCountries(e)),this._storeProjection.getState()})}deleteConsignment(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.deleteConsignment(e,t)),this._storeProjection.getState()})}initializePayment(e,t,i){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(e,t,i)),this._storeProjection.getState()})}forgetCheckout(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.forgetCheckout(e,t)),this._storeProjection.getState()})}remoteCheckoutSignOut(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e,t)),this._storeProjection.getState()})}validateCheckout(e,t){return Dg(this,void 0,void 0,function*(){yield this._checkoutValidator.validate(e,t)})}handlePaymentHumanVerification(e,t){return Dg(this,void 0,void 0,function*(){return"string"==typeof e?this._paymentHumanVerificationHandler.handle(e,null!=t?t:""):this._paymentHumanVerificationHandler.handle(e)})}widgetInteraction(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentStrategyWidgetActionCreator.widgetInteraction(e),{queueId:"widgetInteraction"}),this._storeProjection.getState()})}}class zg{constructor(e){this._transformSelectors=e}create(e){return ct(e,this._transformSelectors)}}function Ng(e){const{config:{getHost:t,getLocale:n}}=e.getState(),r=i({host:t()}),a=new zg(Tg),s=new ti(new Qt(r),new St(new bt(r)),new ni(new ri(r))),d=new Vm(new Qt(r)),c=new cy(e),l=new km(new Em(r),new Vm(new Qt(r))),u=new tt(new at(r),new Cg(new bg(r))),h=new hg(new mg(r),new Qt(r)),p=new zm(new Nm(r)),m=new ly(new uy(Dm(e)),l,new Dy,new Jm(vi(o()))),y=new Jm(vi(o())),g=new Ht(new $t(r),s,new ui(vi(o()),new fi(r))),v=new wg(new Ig(r)),f=new Ot(new zt(r)),S=vi(o()),w=new fi(r),I=new ui(S,w),_=new sg(r),C=new dg,b=new vg(new fg(r,{locale:n()}),e),P=new lg(new ug(r),s),O=new Bm;return new Mg(e,a,s,d,c,l,u,h,p,m,y,g,_,v,f,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"}(kg||(kg={}));class xg{constructor(e){this._instrumentRequestSender=e}loadInstruments(){return e=>oe.create(t=>{t.next(l(kg.LoadInstrumentsRequested));const i=this._getSessionContext(e),n=this._getCurrentAccessToken(e),r=this._getShippingAddress(e);return this._getValidAccessToken(n).then(e=>this._instrumentRequestSender.loadInstruments(Object.assign(Object.assign({},i),{authToken:e.vaultAccessToken}),r).then(({body:i})=>{t.next(l(kg.LoadInstrumentsSucceeded,i,e)),t.complete()})).catch(e=>{t.error(h(kg.LoadInstrumentsFailed,e))})})}deleteInstrument(e){return t=>oe.create(i=>{i.next(l(kg.DeleteInstrumentRequested,void 0,{instrumentId:e}));const n=this._getSessionContext(t),r=this._getCurrentAccessToken(t);return this._getValidAccessToken(r).then(t=>this._instrumentRequestSender.deleteInstrument(Object.assign(Object.assign({},n),{authToken:t.vaultAccessToken}),e).then(({body:n})=>{i.next(l(kg.DeleteInstrumentSucceeded,n,Object.assign({instrumentId:e},t))),i.complete()})).catch(t=>{i.error(h(kg.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(),i=t.getInstrumentsMeta();if(i)return{vaultAccessToken:i.vaultAccessToken,vaultAccessExpiry:i.vaultAccessExpiry}}_getValidAccessToken(e){return e&&this._isValidVaultAccessToken(e)?Promise.resolve(e):this._instrumentRequestSender.getVaultAccessToken().then(({body:e})=>e)}_getShippingAddress(e){const t=e.getState(),i=t.shippingAddress.getShippingAddresses();return i.length>1?i:t.shippingAddress.getShippingAddress()}_getSessionContext(e){const t=e.getState(),i=t.config.getStoreConfig(),n=t.cart.getCart();if(!i)throw new Xe(We.MissingCheckoutConfig);if(!n)throw new Xe(We.MissingCart);const{customerId:r}=n,{storeId:o}=i.storeProfile,{code:a}=i.shopperCurrency.isTransactional?i.shopperCurrency:i.currency;return{customerId:r,storeId:o,currencyCode:a}}}var Fg,Rg,Lg=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i};class Bg{transformResponse(e){const t=this._transformResponse(e),{body:i}=t,n=Lg(t,["body"]);return Object.assign(Object.assign({},n),{body:{vaultedInstruments:this._transformVaultedInstruments(i.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,i=Lg(e,["data"]);return Object.assign(Object.assign({},i),{body:t})}}class jg{constructor(e,t){this._client=e,this._requestSender=t,this._transformer=new Bg}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 i=Object.assign(Object.assign({},e),{instrumentId:t});return new Promise((e,t)=>{this._client.deleteShopperInstrument(i,(i,n)=>i?t(this._transformer.transformErrorResponse(i)):e(this._transformer.transformResponse(n)))})}_loadInstruments(e){return new Promise((t,i)=>{this._client.loadInstruments(e,(e,n)=>e?i(this._transformer.transformErrorResponse(e)):t(this._transformer.transformResponse(n)))})}_loadInstrumentsWithAddress(e,t){const i=Object.assign(Object.assign({},e),{shippingAddress:Array.isArray(t)?t.map(e=>hy(e)):hy(t)});return new Promise((e,t)=>{this._client.loadInstrumentsWithAddress(i,(i,n)=>i?t(this._transformer.transformErrorResponse(i)):e(this._transformer.transformResponse(n)))})}}!function(e){e.LoadPickupOptionsRequested="LOAD_PICKUP_OPTIONS_REQUESTED",e.LoadPickupOptionsSucceeded="LOAD_PICKUP_OPTIONS_SUCCEEDED",e.LoadPickupOptionsFailed="LOAD_PICKUP_OPTIONS_FAILED"}(Fg||(Fg={}));class Ug{constructor(e){this._pickupOptionRequestSender=e}loadPickupOptions(e){return t=>new oe(i=>{const n=this._hydrateApiQuery(t,e);i.next(l(Fg.LoadPickupOptionsRequested)),this._pickupOptionRequestSender.fetchPickupOptions(n).then(t=>{i.next(l(Fg.LoadPickupOptionsSucceeded,t.body.results,e)),i.complete()}).catch(e=>{i.error(h(Fg.LoadPickupOptionsFailed,e))})})}_hydrateApiQuery(e,t){const i=e.getState(),n=i.cart.getCartOrThrow();if(!n)throw new Xe(We.MissingCart);const r=i.consignments.getConsignmentById(t.consignmentId);if(!r)throw new Xe(We.MissingConsignments);const o=r.lineItemIds,a=n.lineItems.physicalItems.filter(e=>P(o,e.id)).map(e=>({variantId:e.variantId,quantity:e.quantity}));return{searchArea:t.searchArea,items:a}}}class qg{constructor(e){this._requestSender=e}fetchPickupOptions(e){return this._requestSender.post("/api/storefront/pickup-options",{headers:Object.assign({Accept:nt.Json},rt),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"}(Rg||(Rg={}));class Vg{constructor(e){this._strategyRegistry=e}updateAddress(e,t){return i=>oe.create(n=>{const r=i.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;n.next(l(Rg.UpdateAddressRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).updateAddress(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{n.next(l(Rg.UpdateAddressSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Rg.UpdateAddressFailed,e,{methodId:o}))})})}selectOption(e,t){return i=>oe.create(n=>{const r=i.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;n.next(l(Rg.SelectOptionRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).selectOption(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{n.next(l(Rg.SelectOptionSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Rg.SelectOptionFailed,e,{methodId:o}))})})}initialize(e){return t=>oe.create(i=>{const n=t.getState(),r=n.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId,a=Object.assign(Object.assign({},e),{methodId:o});if(o&&n.shippingStrategies.isInitialized(o))return i.complete();i.next(l(Rg.InitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).initialize(a).then(()=>{i.next(l(Rg.InitializeSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Rg.InitializeFailed,e,{methodId:o}))})})}deinitialize(e){return t=>oe.create(i=>{const n=t.getState(),r=n.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId;if(o&&!n.shippingStrategies.isInitialized(o))return i.complete();i.next(l(Rg.DeinitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).deinitialize(Object.assign(Object.assign({},e),{methodId:o})).then(()=>{i.next(l(Rg.DeinitializeSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Rg.DeinitializeFailed,e,{methodId:o}))})})}widgetInteraction(e,t){return oe.create(i=>{const n={methodId:t&&t.methodId};i.next(l(Rg.WidgetInteractionStarted,void 0,n)),e().then(()=>{i.next(l(Rg.WidgetInteractionFinished,void 0,n)),i.complete()}).catch(e=>{i.error(h(Rg.WidgetInteractionFailed,e,n))})})}}var Gg,Hg=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class $g{constructor(e,t,i,n,r){this._store=e,this._consignmentActionCreator=t,this._paymentMethodActionCreator=i,this._amazonPayV2PaymentProcessor=n,this._shippingStrategyActionCreator=r}updateAddress(e,t){const i=this._store.getState().shippingAddress.getShippingAddress();if(!i)throw new Xe(We.MissingShippingAddress);const n=Object.assign(Object.assign({},i),{customFields:e.customFields});return this._store.dispatch(this._consignmentActionCreator.updateAddress(n,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return Hg(this,void 0,void 0,function*(){const{amazonpay:t,methodId:i}=e;if(!t||!i)throw new Lt('Unable to proceed because "options.amazonpay" argument is not provided.');const n=(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i))).paymentMethods.getPaymentMethodOrThrow(i);yield this._amazonPayV2PaymentProcessor.initialize(n);const{paymentToken:r,region:o}=n.initializationData,a=t.editAddressButtonId;if(r&&a){const e=this._shouldShowLoadingSpinner(o);this._bindEditButton(a,r,"changeAddress",e)}return this._store.getState()})}deinitialize(){return Hg(this,void 0,void 0,function*(){return yield this._amazonPayV2PaymentProcessor.deinitialize(),Promise.resolve(this._store.getState())})}_bindEditButton(e,t,i,n){const r=document.getElementById(e);if(r&&r.parentNode){if(n){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>this._showLoadingSpinner())}this._amazonPayV2PaymentProcessor.bindButton(e,t,i)}}_showLoadingSpinner(){return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction(()=>new Promise(pe)),{queueId:"widgetInteraction"})}_shouldShowLoadingSpinner(e){return"us"!==e}}!function(e){e.CVV="cvv",e.PAN="pan"}(Gg||(Gg={}));var Wg=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Yg{constructor(e,t,i,n,r,o){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=i,this._paymentMethodActionCreator=n,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 Wg(this,void 0,void 0,function*(){const{methodId:i,braintreefastlane:n,fastlane:r}=e||{},o=r||n,{onPayPalFastlaneAddressChange:a}=o||{};if(!i)throw new Lt('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(i),{clientToken:n,isFastlaneStylingEnabled:r}=(null==e?void 0:e.initializationData)||{};n||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i)));const a=Po(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(i,a)}"function"==typeof a&&(yield this._shouldUseBraintreeFastlaneShippingComponent(i))&&a(()=>this._handleBraintreeFastlaneShippingAddressChange())}catch(e){}return Promise.resolve(this._store.getState())})}_shouldRunAuthenticationFlow(){var e;const t=this._store.getState(),i=null===(e=t.cart.getCart())||void 0===e?void 0:e.id,n=Nr.get("bc-fastlane-sessionId")||"",r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=vl(r)?r:{};return(null==o?void 0:o.authenticationState)!==Tn.CANCELED&&!(null==o?void 0:o.authenticationState)&&n===i}_runAuthenticationFlowOrThrow(e,t){var i,n;return Wg(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 Xe(We.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===(i=r.customer.getCustomer())||void 0===i?void 0:i.email)||(null===(n=r.billingAddress.getBillingAddress())||void 0===n?void 0:n.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===Tn.CANCELED)return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:[],instruments:[]})),void Nr.remove("bc-fastlane-sessionId");const v=this._getPayPalBillingAddress(g),f=g.shippingAddress,S=g.shippingAddress.phoneNumber,w=this._mapPayPalToBcAddress(f,a,S),I=this._mapPayPalToBcAddress(v,a,S);if(I&&w){const t=this._mergeShippingAndBillingAddresses(w,I),i=this._mapPayPalToBcInstrument(e,g.card),n=i?[i]:[];yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:t,instruments:n})),I&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},I),{id:String(I.id)})))),w&&o.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(w)))}})}_getPayPalBillingAddress(e){const{name:t,card:i}=e,n=i.paymentSource.card.billingAddress;return Object.assign(Object.assign({},n),{firstName:n.firstName||(null==t?void 0:t.firstName),lastName:n.lastName||(null==t?void 0:t.lastName)})}_getCountryNameByCountryCode(e,t){const i=t.find(t=>t.code===e);return(null==i?void 0:i.name)||""}_mapPayPalToBcAddress(e,t,i,n){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:i||"",customFields:n||[]}}_normalizeAddress(e){return G(e,["id"])}_mergeShippingAndBillingAddresses(e,t){return A(this._normalizeAddress(e),this._normalizeAddress(t))?[e]:[e,t]}_mapPayPalToBcInstrument(e,t){if(!t)return;const{id:i,paymentSource:n}=t,{brand:r,expiry:o,lastDigits:a}=n.card,[s,d]=o.split("-");return{bigpayToken:i,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Gg.CVV,type:"card"}}_handleBraintreeFastlaneShippingAddressChange(){var e;return Wg(this,void 0,void 0,function*(){const t=this._store.getState().countries.getCountries()||[],i=yield this._braintreeIntegrationService.getBraintreeFastlane(),{selectionChanged:n,selectedAddress:r}=yield i.profile.showShippingAddressSelector();if(n){const i=this._store.getState(),n=i.shippingAddress.getShippingAddressesOrThrow(),o=i.paymentProviderCustomer.getPaymentProviderCustomer(),a=vl(o)?o:{},s=this._mapPayPalToBcAddress(r,t,r.phoneNumber,null===(e=n[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 A(this._normalizeAddress(e),this._normalizeAddress(t))}_shouldUseBraintreeFastlaneShippingComponent(e){var t;return Wg(this,void 0,void 0,function*(){const i=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomer(),n=vl(i)?i:{};if(n&&n!==Tn.CANCELED){const i=yield this._getBraintreePaymentMethodOrThrow(e);return!!(null===(t=null==i?void 0:i.initializationData)||void 0===t?void 0:t.isFastlaneEnabled)}return!1})}_getBraintreePaymentMethodOrThrow(e){return Wg(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 Kg{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 Jg=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Zg{constructor(e,t,i,n,r,o,a){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=i,this._paymentMethodActionCreator=n,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 Jg(this,void 0,void 0,function*(){const{methodId:t,paypalcommercefastlane:i,fastlane:n}=e||{},r=n||i,{onPayPalFastlaneAddressChange:o,styles:a}=r||{};if(!t)throw new Lt('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 Jg(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!==Ms.CANCELED}_initializePayPalSdk(e,t){var i;return Jg(this,void 0,void 0,function*(){const n=this._store.getState().cart.getCartOrThrow(),r=yield this._getPayPalPaymentMethodOrThrow(e),{isDeveloperModeApplicable:o,isFastlaneStylingEnabled:a}=(null==r?void 0:r.initializationData)||{},s=!!o,d=qs(a?null===(i=null==r?void 0:r.initializationData)||void 0===i?void 0:i.fastlaneStyles:{},t),c=yield this._paypalSdkScriptLoader.getPayPalFastlaneSdk(r,n.currency.code,n.id);yield this._paypalCommerceFastlaneUtils.initializePayPalFastlane(c,s,d)})}_authenticateUserWithFastlaneOtp(e){var t,i;return Jg(this,void 0,void 0,function*(){const n=this._store.getState(),r=n.cart.getCartOrThrow(),o=null===(t=n.customer.getCustomer())||void 0===t?void 0:t.email,a=null===(i=n.billingAddress.getBillingAddress())||void 0===i?void 0:i.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===Ms.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 Jg(this,void 0,void 0,function*(){const t=this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:i,selectedAddress:n}=yield t.profile.showShippingAddressSelector();if(i){const t=this._store.getState(),i=t.shippingAddress.getShippingAddressesOrThrow(),r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=cp(r)?r:{},a=this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(n.address,n.name,n.phoneNumber,null===(e=i[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 Xg;class Qg{constructor(e,t,i,n){this._store=e,this._stripeScriptLoader=t,this._consignmentActionCreator=i,this._paymentMethodActionCreator=n}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,i=void 0,r=function*(){if(!e.stripeupe)throw new Lt('Unable to proceed because "options" argument is not provided.');const{container:t,gatewayId:i,methodId:n,onChangeShipping:r,getStyles:o,availableCountries:a,getStripeState:s}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new Lt(`Unable to proceed because "${e}" argument is not provided.`)});const d=yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i,{params:{method:n}})),c=d.paymentMethods.getPaymentMethodOrThrow(n,i),{initializationData:l}=c;if(!c||!c.initializationData.stripePublishableKey||!c.clientToken)throw new Xe(We.MissingPaymentMethod);let u;this._stripeUPEClient=yield this._stripeScriptLoader.getStripeClient(l,d.cart.getLocale(),ba.V3,Da,Ma);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(),v=y.find(e=>"phone"===e.name);let f={mode:Sa.SHIPPING,allowedCountries:[a],fields:{phone:"always"},validation:{phone:{required:v&&v.required?"always":"never"}},display:{name:wa.SPLIT}};if(g){const{stateOrProvinceCode:e,countryCode:t,lastName:i,firstName:n,phone:r,address1:o,address2:a,city:d,postalCode:c}=g,l=e&&t?s(t,e):e;f=Object.assign(Object.assign({},f),{defaultValues:{firstName:n,lastName:i,phone:r,address:{line1:o,line2:a,city:d,state:l,postal_code:c,country:t}}})}let S=this._stripeElements.getElement(Pa.SHIPPING);return S&&S.destroy(),S=this._stripeElements.create(Pa.SHIPPING,f),S.on(Ea.CHANGE,e=>{if(!("isNewAddress"in e))throw new Xe(We.MissingShippingAddress);(e.complete||e.isNewAddress)&&(this.sendData&&clearTimeout(this.sendData),this.sendData=setTimeout(()=>{r(Object.assign(Object.assign({},e),{phoneFieldRequired:!!v&&v.required}))},1e3))}),S.mount(`#${t}`),Promise.resolve(this._store.getState())},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,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"}(Xg||(Xg={}));class ev{constructor(e){this._requestSender=e}sendSignInEmail(e,t){return se(me(l(Xg.SendSignInEmailRequested)),de(()=>{return i=this,n=void 0,o=function*(){const{body:i}=yield this._requestSender.sendSignInEmail(e,t);return l(Xg.SendSignInEmailSucceeded,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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).pipe(ge(e=>Je(Xg.SendSignInEmailFailed,e)))}}class tv{constructor(e){this._requestSender=e}sendSignInEmail({email:e,redirectUrl:t},{timeout:i}={}){const n=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post("/login.php?action=passwordless_login",{body:{email:e,redirect_url:t||wi(window.top?window.top.location.href:"").pathname},headers:n,timeout:i})}}class iv{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 nv=class{constructor(e,t,i,n,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,w,I,_,C,b,P,O,E){this._store=e,this._storeProjection=t,this._extensionMessenger=i,this._extensionEventBroadcaster=n,this._billingAddressActionCreator=r,this._checkoutActionCreator=o,this._configActionCreator=a,this._customerActionCreator=s,this._consignmentActionCreator=d,this._countryActionCreator=c,this._couponActionCreator=l,this._customerStrategyActionCreator=u,this._errorActionCreator=h,this._giftCertificateActionCreator=p,this._instrumentActionCreator=m,this._orderActionCreator=y,this._paymentMethodActionCreator=g,this._paymentStrategyActionCreator=v,this._pickupOptionActionCreator=f,this._shippingCountryActionCreator=S,this._shippingStrategyActionCreator=w,this._signInEmailActionCreator=I,this._spamProtectionActionCreator=_,this._storeCreditActionCreator=C,this._subscriptionsActionCreator=b,this._formFieldsActionCreator=P,this._extensionActionCreator=O,this._workerExtensionMessenger=E,this._errorTransformer=function(e="development"===ht()){return new iv(t=>{if(!e||!function(e){return!(!e.subtype&&!e.type)}(t))return t.message;switch(t.subtype||t.type){case We.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 We.MissingCart:case We.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 We.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 We.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 We.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 We.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 si.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 si.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 si.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 i=this._checkoutActionCreator.updateCheckout(e,t);return this._dispatch(i)}loadOrder(e,t){const i=this._orderActionCreator.loadOrder(e,t),n=this._formFieldsActionCreator.loadFormFields(t),r=this._configActionCreator.loadConfig(t);return Promise.all([this._dispatch(i),this._dispatch(r,{queueId:"config"}),this._dispatch(n,{queueId:"formFields"})]).then(()=>this.getState())}submitOrder(e,t){const i=this._paymentStrategyActionCreator.execute(e,t);return this._dispatch(i,{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 i=this._paymentMethodActionCreator.loadPaymentMethodsById(e,t);return this._dispatch(i,{queueId:"paymentMethods"})}loadPaymentMethod(e,t){const i=this._paymentMethodActionCreator.loadPaymentMethod(e,t);return this._dispatch(i,{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 i=this._signInEmailActionCreator.sendSignInEmail(e,t);return this._dispatch(i,{queueId:"signInEmail"})}createCustomerAccount(e,t){const i=this._customerActionCreator.createCustomer(e,t);return this._dispatch(i)}createCustomerAddress(e,t){const i=this._customerActionCreator.createAddress(e,t);return this._dispatch(i)}updateSubscriptions(e,t){const i=this._subscriptionsActionCreator.updateSubscriptions(e,t);return this._dispatch(i,{queueId:"subscriptions"})}continueAsGuest(e,t){const i=this._billingAddressActionCreator.continueAsGuest(e,t);return this._dispatch(i)}signInCustomer(e,t){const i=this._customerStrategyActionCreator.signIn(e,t);return this._dispatch(i,{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 i=this._shippingStrategyActionCreator.selectOption(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}updateShippingAddress(e,t){const i=this._shippingStrategyActionCreator.updateAddress(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}createConsignments(e,t){const i=this._consignmentActionCreator.createConsignments(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}deleteConsignment(e,t){const i=this._consignmentActionCreator.deleteConsignment(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}updateConsignment(e,t){const i=this._consignmentActionCreator.updateConsignment(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}assignItemsToAddress(e,t){const i=this._consignmentActionCreator.assignItemsByAddress(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}unassignItemsToAddress(e,t){const i=this._consignmentActionCreator.unassignItemsByAddress(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}selectConsignmentShippingOption(e,t,i){const n=this._consignmentActionCreator.updateShippingOption({id:e,shippingOptionId:t},i);return this._dispatch(n,{queueId:"shippingStrategy"})}updateBillingAddress(e,t={}){const i=this._billingAddressActionCreator.updateAddress(e,t);return this._dispatch(i)}applyStoreCredit(e,t){const i=this._storeCreditActionCreator.applyStoreCredit(e,t);return this._dispatch(i)}applyCoupon(e,t){const i=this._couponActionCreator.applyCoupon(e,t);return this._dispatch(i)}removeCoupon(e,t){const i=this._couponActionCreator.removeCoupon(e,t);return this._dispatch(i)}applyGiftCertificate(e,t){const i=this._giftCertificateActionCreator.applyGiftCertificate(e,t);return this._dispatch(i)}removeGiftCertificate(e,t){const i=this._giftCertificateActionCreator.removeGiftCertificate(e,t);return this._dispatch(i)}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 i=this,n=void 0,o=function*(){const i=this._extensionActionCreator.renderExtension(e,t,this._workerExtensionMessenger),n=yield this._dispatch(i,{queueId:"extensions"});return this._extensionEventBroadcaster.listen(),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}clearExtensionCache(e){this._extensionMessenger.clearCacheByRegion(e)}postMessageToExtension(e,t){this._extensionMessenger.post(e,t)}handleExtensionCommand(e,t,i){return this._extensionMessenger.listenForCommand(e,t,i)}handleExtensionQuery(e,t,i){return this._extensionMessenger.listenForQuery(e,t,i)}_dispatch(e,t){return this._store.dispatch(e,t).then(()=>this.getState()).catch(e=>{throw this._errorTransformer.transform(e)})}};nv=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],nv);const rv=nv;function ov(e){return(...t)=>{const i=t.pop();return e(...t,(...e)=>{const t=i(...e);return"function"==typeof t?Pe(t):t})}}const av=ov(Fe),sv=ov(Re(Le,(e,t)=>Be(e,t)));class dv extends It{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 cv(e){return e.reduce((e,t)=>t?[...e,t]:e,[]).join(" ")}class lv extends It{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}class uv{constructor(){this._factoryMethods={},this.register("default",(e,t)=>new It(e,{message:t})),this.register("internal",(e,t)=>function(e,t){const{body:i}=e,{errors:n=[]}=i;return new It(e,{message:cv(n)||i.detail||i.title||t,errors:n.length?n.map(e=>({code:i.type,message:e})):[{code:i.type,message:i.detail||i.title}]})}(e,t)),this.register("storefront",(e,t)=>function(e,t){const{body:i}=e;return new It(e,{message:t||i.detail||i.title,errors:[{code:i.code||i.type,message:i.detail||i.title}]})}(e,t)),this.register("payment",(e,t)=>Zm(e,t)),this.register("timeout",e=>new lv(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=L(e.body.type.split("/"));return t&&this._factoryMethods[t]?t:"internal"}const t=L(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 hv(e,t){return Array.isArray(e)?e.map(e=>hv(e,t)):M(e)?Q(H(e,t),(e,i,n)=>{e[n]=hv(i,t)},{}):e}function pv(e,t){return function(e){return e.type===dt.ClearError}(t)?hv(e,e=>e===t.payload):e}function mv(e,t,i){return e===t||(e&&t&&"object"==typeof e&&"object"==typeof t?Array.isArray(e)&&Array.isArray(t)?function(e,t,i){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(!mv(e[n],t[n],i))return!1;return!0}(e,t,i):!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,i){const n=i&&i.keyFilter,r=n?Object.keys(e).filter(n):Object.keys(e),o=n?Object.keys(t).filter(n):Object.keys(t);if(r.length!==o.length)return!1;for(let n=0,o=r.length;n<o;n++){const o=r[n];if(!Object.prototype.hasOwnProperty.call(t,o))return!1;if(!mv(e[o],t[o],i))return!1}return!0}(e,t,i))):e===t)}function yv(e,t){return void 0===t||mv(e,t)?e:t}function gv(e,t,i){return e&&Object.prototype.hasOwnProperty.call(e,t)&&mv(e[t],i)?e:Object.assign(Object.assign({},e),{[t]:i})}const vv={errors:{},statuses:{}};function fv(e=vv,t){return d({data:Sv,errors:c(wv,pv),statuses:Iv})(e,t)}function Sv(e,t){var i,n;switch(t.type){case Ye.UpdateBillingAddressSucceeded:case Ye.ContinueAsGuestSucceeded:case Vt.LoadCheckoutSucceeded:return yv(e,t.payload&&t.payload.billingAddress);case Gt.HydrateInitialState:return yv(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.billingAddress);default:return e}}function wv(e=vv.errors,t){switch(t.type){case Vt.LoadCheckoutRequested:case Vt.LoadCheckoutSucceeded:return gv(e,"loadError",void 0);case Vt.LoadCheckoutFailed:return gv(e,"loadError",t.payload);case Ye.UpdateBillingAddressRequested:case Ye.UpdateBillingAddressSucceeded:return gv(e,"updateError",void 0);case Ye.UpdateBillingAddressFailed:return gv(e,"updateError",t.payload);case Sg.UpdateSubscriptionsRequested:case Sg.UpdateSubscriptionsSucceeded:case Ye.ContinueAsGuestRequested:case Ye.ContinueAsGuestSucceeded:return gv(e,"continueAsGuestError",void 0);case Sg.UpdateSubscriptionsFailed:case Ye.ContinueAsGuestFailed:return gv(e,"continueAsGuestError",t.payload);default:return e}}function Iv(e=vv.statuses,t){switch(t.type){case Vt.LoadCheckoutRequested:return gv(e,"isLoading",!0);case Vt.LoadCheckoutSucceeded:case Vt.LoadCheckoutFailed:return gv(e,"isLoading",!1);case Ye.UpdateBillingAddressRequested:return gv(e,"isUpdating",!0);case Ye.UpdateBillingAddressFailed:case Ye.UpdateBillingAddressSucceeded:return gv(e,"isUpdating",!1);case Ye.ContinueAsGuestRequested:case Sg.UpdateSubscriptionsRequested:return gv(e,"isContinuingAsGuest",!0);case Sg.UpdateSubscriptionsSucceeded:case Sg.UpdateSubscriptionsFailed:case Ye.ContinueAsGuestFailed:case Ye.ContinueAsGuestSucceeded:return gv(e,"isContinuingAsGuest",!1);default:return e}}const _v=function e(t,i,n){const{matchObject:r=(e,t)=>void 0!==e.id&&e.id===t.id}=n||{};if(!t)return i;if(!i||t===i)return t;let o=0,a=0;const s=(e,t,i)=>(o+=e===t?1:0,a+=e===i?1:0,e),d=i.map((i,n)=>{const o=t&&t[n];return Pg(o)&&Pg(i)?r(o,i)?s(Cv(o,i),o,i):s(yv(o,i),o,i):O(o)&&O(i)?s(e(o,i),o,i):s(yv(o,i),o,i)});return o===i.length&&t&&t.length===i.length?t:a===i.length?i:d},Cv=function e(t,i){return t?i&&t!==i?Object.keys(i).reduce((t,n)=>{const r=t[n],o=i[n];return Pg(r)&&Pg(o)?gv(t,n,e(r,o)):O(r)&&O(o)?gv(t,n,_v(r,o)):gv(t,n,o)},t):t:i},bv={errors:{},statuses:{}};function Pv(e=bv,t){return d({data:Ov,errors:c(Av,pv),statuses:Ev})(e,t)}function Ov(e,t){var i,n;switch(t.type){case Ye.UpdateBillingAddressSucceeded:case Vt.LoadCheckoutSucceeded:case cg.CreateConsignmentsSucceeded:case cg.DeleteConsignmentSucceeded:case cg.UpdateConsignmentSucceeded:case cg.UpdateShippingOptionSucceeded:case cg.LoadShippingOptionsSucceeded:case Pt.ApplyCouponSucceeded:case Pt.RemoveCouponSucceeded:case Tt.ApplyGiftCertificateSucceeded:case Tt.RemoveGiftCertificateSucceeded:return Cv(e,t.payload&&t.payload.cart);case Gt.HydrateInitialState:return Cv(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.cart);default:return e}}function Ev(e=bv.statuses,t){switch(t.type){case Vt.LoadCheckoutRequested:return gv(e,"isLoading",!0);case Vt.LoadCheckoutFailed:case Vt.LoadCheckoutSucceeded:return gv(e,"isLoading",!1);default:return e}}function Av(e=bv.errors,t){switch(t.type){case Vt.LoadCheckoutRequested:case Vt.LoadCheckoutSucceeded:return gv(e,"loadError",void 0);case Vt.LoadCheckoutFailed:return gv(e,"loadError",t.payload);default:return e}}var Tv;!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"}(Tv||(Tv={}));const kv={data:{},errors:{},statuses:{}},Dv={initializedContainers:{}},Mv={},zv={};function Nv(e=kv,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:xv}),errors:d({[t.meta.methodId]:Fv}),statuses:d({[t.meta.methodId]:Rv})})(e,t):e}function xv(e=Dv,t){switch(t.type){case Tv.InitializeButtonSucceeded:return t.meta&&t.meta.containerId?Cv(e,{initializedContainers:{[t.meta.containerId]:!0}}):e;case Tv.DeinitializeButtonSucceeded:return gv(e,"initializedContainers",{})}return e}function Fv(e=Mv,t){switch(t.type){case Tv.InitializeButtonRequested:case Tv.InitializeButtonSucceeded:return gv(e,"initializeError",void 0);case Tv.InitializeButtonFailed:return gv(e,"initializeError",t.payload);case Tv.DeinitializeButtonRequested:case Tv.DeinitializeButtonSucceeded:return gv(e,"deinitializeError",void 0);case Tv.DeinitializeButtonFailed:return gv(e,"deinitializeError",t.payload);default:return e}}function Rv(e=zv,t){switch(t.type){case Tv.InitializeButtonRequested:return gv(e,"isInitializing",!0);case Tv.InitializeButtonFailed:case Tv.InitializeButtonSucceeded:return gv(e,"isInitializing",!1);case Tv.DeinitializeButtonRequested:return gv(e,"isDeinitializing",!0);case Tv.DeinitializeButtonFailed:case Tv.DeinitializeButtonSucceeded:return gv(e,"isDeinitializing",!1);default:return e}}const Lv={meta:{},errors:{},statuses:{}};function Bv(e=Lv,t){return d({data:jv,errors:c(Uv,pv),statuses:qv})(e,t)}function jv(e,t){var i;switch(t.type){case ft.LoadConfigSucceeded:return Cv(e,t.payload);case Gt.HydrateInitialState:return Cv(e,null===(i=t.payload)||void 0===i?void 0:i.config);default:return e}}function Uv(e=Lv.errors,t){switch(t.type){case ft.LoadConfigSucceeded:return gv(e,"loadError",void 0);case ft.LoadConfigFailed:return gv(e,"loadError",t.payload);default:return e}}function qv(e=Lv.statuses,t){switch(t.type){case ft.LoadConfigRequested:return gv(e,"isLoading",!0);case ft.LoadConfigSucceeded:case ft.LoadConfigFailed:return gv(e,"isLoading",!1);default:return e}}const Vv={errors:{},statuses:{}};function Gv(e=Vv,t){return d({data:Hv,errors:c($v,pv),statuses:Wv})(e,t)}function Hv(e,t){var i,n;switch(t.type){case Vt.LoadCheckoutSucceeded:case Pt.ApplyCouponSucceeded:case cg.UpdateShippingOptionSucceeded:case Pt.RemoveCouponSucceeded:case wm.LoadOrderSucceeded:return _v(e,t.payload&&t.payload.coupons);case Gt.HydrateInitialState:return _v(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.coupons);default:return e}}function $v(e={},t){switch(t.type){case Pt.ApplyCouponRequested:case Pt.ApplyCouponSucceeded:return gv(e,"applyCouponError",void 0);case Pt.ApplyCouponFailed:return gv(e,"applyCouponError",t.payload);case Pt.RemoveCouponRequested:case Pt.RemoveCouponSucceeded:return gv(e,"removeCouponError",void 0);case Pt.RemoveCouponFailed:return gv(e,"removeCouponError",t.payload);default:return e}}function Wv(e={},t){switch(t.type){case Pt.ApplyCouponRequested:return gv(e,"isApplyingCoupon",!0);case Pt.ApplyCouponSucceeded:case Pt.ApplyCouponFailed:return gv(e,"isApplyingCoupon",!1);case Pt.RemoveCouponRequested:return gv(e,"isRemovingCoupon",!0);case Pt.RemoveCouponSucceeded:case Pt.RemoveCouponFailed:return gv(e,"isRemovingCoupon",!1);default:return e}}const Yv={errors:{},statuses:{}};function Kv(e=Yv,t){return d({data:Jv,errors:c(Zv,pv),statuses:Xv})(e,t)}function Jv(e,t){var i,n;switch(t.type){case Vt.LoadCheckoutSucceeded:case cg.CreateConsignmentsSucceeded:case cg.UpdateConsignmentSucceeded:case cg.DeleteConsignmentSucceeded:case cg.UpdateShippingOptionSucceeded:case Pt.ApplyCouponSucceeded:case Pt.RemoveCouponSucceeded:case Tt.ApplyGiftCertificateSucceeded:case Tt.RemoveGiftCertificateSucceeded:return _v(e,t.payload&&t.payload.giftCertificates);case Gt.HydrateInitialState:return _v(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.giftCertificates);default:return e}}function Zv(e=Yv.errors,t){switch(t.type){case Tt.ApplyGiftCertificateRequested:case Tt.ApplyGiftCertificateSucceeded:return gv(e,"applyGiftCertificateError",void 0);case Tt.ApplyGiftCertificateFailed:return gv(e,"applyGiftCertificateError",t.payload);case Tt.RemoveGiftCertificateRequested:case Tt.RemoveGiftCertificateSucceeded:return gv(e,"removeGiftCertificateError",void 0);case Tt.RemoveGiftCertificateFailed:return gv(e,"removeGiftCertificateError",t.payload);default:return e}}function Xv(e=Yv.statuses,t){switch(t.type){case Tt.ApplyGiftCertificateRequested:return gv(e,"isApplyingGiftCertificate",!0);case Tt.ApplyGiftCertificateSucceeded:case Tt.ApplyGiftCertificateFailed:return gv(e,"isApplyingGiftCertificate",!1);case Tt.RemoveGiftCertificateRequested:return gv(e,"isRemovingGiftCertificate",!0);case Tt.RemoveGiftCertificateSucceeded:case Tt.RemoveGiftCertificateFailed:return gv(e,"isRemovingGiftCertificate",!1);default:return e}}const Qv={errors:{},statuses:{}};function ef(e=Qv,t){return d({data:tf,errors:c(nf,pv),statuses:rf})(e,t)}function tf(e,t){var i,n;switch(t.type){case Ye.ContinueAsGuestSucceeded:case Vt.LoadCheckoutSucceeded:return Cv(e,t.payload&&t.payload.customer);case Dt.CreateCustomerAddressSucceeded:return Cv(e,t.payload);case Gt.HydrateInitialState:return Cv(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.customer);default:return e}}function nf(e=Qv.errors,t){switch(t.type){case Dt.CreateCustomerRequested:case Dt.CreateCustomerSucceeded:return gv(e,"createError",void 0);case Dt.CreateCustomerFailed:return gv(e,"createError",t.payload);case Dt.CreateCustomerAddressRequested:case Dt.CreateCustomerAddressSucceeded:return gv(e,"createAddressError",void 0);case Dt.CreateCustomerAddressFailed:return gv(e,"createAddressError",t.payload);default:return e}}function rf(e=Qv.statuses,t){switch(t.type){case Dt.CreateCustomerRequested:return gv(e,"isCreating",!0);case Dt.CreateCustomerFailed:case Dt.CreateCustomerSucceeded:return gv(e,"isCreating",!1);case Dt.CreateCustomerAddressRequested:return gv(e,"isCreatingAddress",!0);case Dt.CreateCustomerAddressFailed:case Dt.CreateCustomerAddressSucceeded:return gv(e,"isCreatingAddress",!1);default:return e}}const of={data:{},errors:{},statuses:{}};function af(e=of,t){return d({data:sf,errors:c(df,pv),statuses:cf})(e,t)}function sf(e=of.data,t){switch(t.type){case qt.InitializeSucceeded:return Cv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case qt.DeinitializeSucceeded:return Cv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function df(e=of.errors,t){switch(t.type){case qt.InitializeRequested:case qt.InitializeSucceeded:return Cv(e,{initializeErrors:Object.assign({},e.initializeErrors),initializeMethodId:e.initializeMethodId?e.initializeMethodId:void 0});case qt.InitializeFailed:return Cv(e,{initializeErrors:Object.assign(Object.assign({},e.initializeErrors),{[t.meta&&t.meta.methodId]:t.payload}),initializeMethodId:t.meta&&t.meta.methodId});case qt.DeinitializeRequested:case qt.DeinitializeSucceeded:return Cv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case qt.DeinitializeFailed:return Cv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case qt.SignInRequested:case qt.SignInSucceeded:return Cv(e,{signInError:void 0,signInMethodId:void 0});case qt.SignInFailed:return Cv(e,{signInError:t.payload,signInMethodId:t.meta&&t.meta.methodId});case qt.SignOutRequested:case qt.SignOutSucceeded:return Cv(e,{signOutError:void 0,signOutMethodId:void 0});case qt.SignOutFailed:return Cv(e,{signOutError:t.payload,signOutMethodId:t.meta&&t.meta.methodId});case qt.ExecutePaymentMethodCheckoutRequested:case qt.ExecutePaymentMethodCheckoutSucceeded:return Cv(e,{executePaymentMethodCheckoutError:void 0,executePaymentMethodCheckoutMethodId:void 0});case qt.ExecutePaymentMethodCheckoutFailed:return Cv(e,{executePaymentMethodCheckoutError:t.payload,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case qt.WidgetInteractionStarted:case qt.WidgetInteractionFinished:return Cv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case qt.WidgetInteractionFailed:return Cv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function cf(e=of.statuses,t){switch(t.type){case qt.InitializeRequested:return Cv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case qt.InitializeFailed:case qt.InitializeSucceeded:return Cv(e,{isInitializing:!1,initializeMethodId:void 0});case qt.DeinitializeRequested:return Cv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case qt.DeinitializeFailed:case qt.DeinitializeSucceeded:return Cv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case qt.SignInRequested:return Cv(e,{isSigningIn:!0,signInMethodId:t.meta&&t.meta.methodId});case qt.SignInFailed:case qt.SignInSucceeded:return Cv(e,{isSigningIn:!1,signInMethodId:void 0});case qt.SignOutRequested:return Cv(e,{isSigningOut:!0,signOutMethodId:t.meta&&t.meta.methodId});case qt.SignOutFailed:case qt.SignOutSucceeded:return Cv(e,{isSigningOut:!1,signOutMethodId:void 0});case qt.ExecutePaymentMethodCheckoutRequested:return Cv(e,{isExecutingPaymentMethodCheckout:!0,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case qt.ExecutePaymentMethodCheckoutFailed:case qt.ExecutePaymentMethodCheckoutSucceeded:return Cv(e,{isExecutingPaymentMethodCheckout:!1,executePaymentMethodCheckoutMethodId:void 0});case qt.WidgetInteractionStarted:return Cv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case qt.WidgetInteractionFinished:case qt.WidgetInteractionFailed:return Cv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const lf={errors:{},statuses:{}};function uf(e=lf,t){return d({data:hf,errors:c(pf,pv),statuses:mf})(e,t)}function hf(e,t){var i;return t.type===di.LoadExtensionsSucceeded?_v(e,t.payload):t.type===Gt.HydrateInitialState?_v(e,null===(i=t.payload)||void 0===i?void 0:i.extensions):e}function pf(e=lf.errors,t){switch(t.type){case di.LoadExtensionsRequested:case di.LoadExtensionsSucceeded:return gv(e,"loadError",void 0);case di.RenderExtensionRequested:case di.RenderExtensionSucceeded:return gv(e,"renderError",void 0);case di.LoadExtensionsFailed:return gv(e,"loadError",t.payload);case di.RenderExtensionFailed:return gv(e,"renderError",t.payload);default:return e}}function mf(e=lf.statuses,t){switch(t.type){case di.LoadExtensionsRequested:return gv(e,"isLoading",!0);case di.LoadExtensionsSucceeded:case di.LoadExtensionsFailed:return gv(e,"isLoading",!1);default:return e}}const yf={errors:{},statuses:{}};function gf(e=yf,t){return d({data:vf,errors:c(ff,pv),statuses:Sf})(e,t)}function vf(e,t){var i;switch(t.type){case ei.LoadFormFieldsSucceeded:return Cv(e,t.payload);case Gt.HydrateInitialState:return Cv(e,null===(i=t.payload)||void 0===i?void 0:i.formFields);default:return e}}function ff(e=yf.errors,t){switch(t.type){case ei.LoadFormFieldsSucceeded:return gv(e,"loadError",void 0);case ei.LoadFormFieldsFailed:return gv(e,"loadError",t.payload);default:return e}}function Sf(e=yf.statuses,t){switch(t.type){case ei.LoadFormFieldsRequested:return gv(e,"isLoading",!0);case ei.LoadFormFieldsSucceeded:case ei.LoadFormFieldsFailed:return gv(e,"isLoading",!1);default:return e}}const wf={errors:{},statuses:{}};function If(e=wf,t){return d({data:_f,errors:c(Cf,pv),statuses:bf})(e,t)}function _f(e,t){return t.type===Sm.LoadCountriesSucceeded?_v(e,t.payload):e}function Cf(e=wf.errors,t){switch(t.type){case Sm.LoadCountriesRequested:case Sm.LoadCountriesSucceeded:return gv(e,"loadError",void 0);case Sm.LoadCountriesFailed:return gv(e,"loadError",t.payload);default:return e}}function bf(e=wf.statuses,t){switch(t.type){case Sm.LoadCountriesRequested:return gv(e,"isLoading",!0);case Sm.LoadCountriesSucceeded:case Sm.LoadCountriesFailed:return gv(e,"isLoading",!1);default:return e}}const Pf={errors:{},meta:{},statuses:{}};function Of(e=Pf,t){return d({data:Ef,errors:c(Tf,pv),meta:Af,statuses:kf})(e,t)}function Ef(e,t){switch(t.type){case wm.LoadOrderSucceeded:case wm.LoadOrderPaymentsSucceeded:return Cv(e,G(t.payload,["billingAddress","coupons"]));default:return e}}function Af(e,t){switch(t.type){case wm.FinalizeOrderSucceeded:case wm.SubmitOrderSucceeded:return Cv(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 Tf(e=Pf.errors,t){switch(t.type){case wm.LoadOrderRequested:case wm.LoadOrderSucceeded:case wm.LoadOrderPaymentsSucceeded:case wm.LoadOrderPaymentsRequested:return gv(e,"loadError",void 0);case wm.LoadOrderFailed:case wm.LoadOrderPaymentsFailed:return gv(e,"loadError",t.payload);default:return e}}function kf(e=Pf.statuses,t){switch(t.type){case wm.LoadOrderRequested:case wm.LoadOrderPaymentsRequested:return gv(e,"isLoading",!0);case wm.LoadOrderSucceeded:case wm.LoadOrderFailed:case wm.LoadOrderPaymentsSucceeded:case wm.LoadOrderPaymentsFailed:return gv(e,"isLoading",!1);default:return e}}const Df={};function Mf(e=Df,t){return d({data:zf})(e,t)}function zf(e,t){switch(t.type){case wm.LoadOrderPaymentsSucceeded:case wm.LoadOrderSucceeded:return yv(e,t.payload&&t.payload.billingAddress);default:return e}}function Nf(e={},t){return d({data:xf})(e,t)}function xf(e,t){return t.type===ry.SubmitPaymentSucceeded?t.payload:e}const Ff={errors:{},statuses:{}};function Rf(e=Ff,t){return d({data:Lf,errors:c(jf,pv),meta:Bf,statuses:Uf})(e,t)}function Lf(e,t){switch(t.type){case Tm.LoadPaymentMethodSucceeded:return function(e,t,i){if(!t)return e;const n=W(t,"id"),r="object"==typeof i?Y(i):i||n,o=w(e,r),a=[...e];if(-1===o)a.push(t);else{const i=e[o];a[o]=Pg(i)&&Pg(t)?Cv(i,t):t}return a}(e||[],t.payload,t.payload&&{id:t.payload.id,gateway:t.payload.gateway});case Tm.LoadPaymentMethodsSucceeded:return _v(e,t.payload,{matchObject:(e,t)=>e.id===t.id&&e.gateway===t.gateway});default:return e}}function Bf(e,t){return t.type===Tm.LoadPaymentMethodsSucceeded?Cv(e,t.meta):e}function jf(e=Ff.errors,t){switch(t.type){case Tm.LoadPaymentMethodsRequested:case Tm.LoadPaymentMethodsSucceeded:return gv(e,"loadError",void 0);case Tm.LoadPaymentMethodsFailed:return gv(e,"loadError",t.payload);case Tm.LoadPaymentMethodRequested:case Tm.LoadPaymentMethodSucceeded:return Cv(e,{loadMethodId:void 0,loadMethodError:void 0});case Tm.LoadPaymentMethodFailed:return Cv(e,{loadMethodId:t.meta.methodId,loadMethodError:t.payload});default:return e}}function Uf(e=Ff.statuses,t){switch(t.type){case Tm.LoadPaymentMethodsRequested:return gv(e,"isLoading",!0);case Tm.LoadPaymentMethodsSucceeded:case Tm.LoadPaymentMethodsFailed:return gv(e,"isLoading",!1);case Tm.LoadPaymentMethodRequested:return Cv(e,{isLoadingMethod:!0,loadMethodId:t.meta.methodId});case Tm.LoadPaymentMethodSucceeded:case Tm.LoadPaymentMethodFailed:return Cv(e,{isLoadingMethod:!1,loadMethodId:void 0});default:return e}}const qf={data:{},errors:{},statuses:{}};function Vf(e=qf,t){return d({data:Gf,errors:c(Hf,pv),statuses:$f})(e,t)}function Gf(e=qf.data,t){switch(t.type){case Fm.InitializeSucceeded:if(t.meta){const{methodId:i,gatewayId:n}=t.meta,r=n?`${i}.${n}`:i;return Cv(e,{[r]:{isInitialized:!0}})}break;case Fm.DeinitializeSucceeded:if(t.meta){const{methodId:i,gatewayId:n}=t.meta,r=n?`${i}.${n}`:i;return Cv(e,{[r]:{isInitialized:!1}})}}return e}function Hf(e=qf.errors,t){switch(t.type){case Fm.InitializeRequested:case Fm.InitializeSucceeded:return Cv(e,{initializeError:void 0,initializeMethodId:void 0});case Fm.InitializeFailed:{let i=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:n}=t.meta;i=n?`${e}.${n}`:e}return Cv(e,{initializeError:t.payload,initializeMethodId:i})}case Fm.DeinitializeRequested:case Fm.DeinitializeSucceeded:return Cv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Fm.DeinitializeFailed:{let i=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:n}=t.meta;i=n?`${e}.${n}`:e}return Cv(e,{deinitializeError:t.payload,deinitializeMethodId:i})}case Fm.ExecuteRequested:case Fm.ExecuteSucceeded:return Cv(e,{executeError:void 0,executeMethodId:void 0});case Fm.ExecuteFailed:return Cv(e,{executeError:t.payload,executeMethodId:t.meta&&t.meta.methodId});case Fm.FinalizeRequested:case Fm.FinalizeSucceeded:return Cv(e,{finalizeError:void 0,finalizeMethodId:void 0});case Fm.FinalizeFailed:return Cv(e,{finalizeError:t.payload,finalizeMethodId:t.meta&&t.meta.methodId});case Fm.WidgetInteractionStarted:case Fm.WidgetInteractionFinished:return Cv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Fm.WidgetInteractionFailed:return Cv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function $f(e=qf.statuses,t){switch(t.type){case Fm.InitializeRequested:{let i=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:n}=t.meta;i=n?`${e}.${n}`:e}return Cv(e,{isInitializing:!0,initializeMethodId:i})}case Fm.InitializeFailed:case Fm.InitializeSucceeded:return Cv(e,{isInitializing:!1,initializeMethodId:void 0});case Fm.DeinitializeRequested:{let i=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:n}=t.meta;i=n?`${e}.${n}`:e}return Cv(e,{isDeinitializing:!0,deinitializeMethodId:i})}case Fm.DeinitializeFailed:case Fm.DeinitializeSucceeded:return Cv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Fm.ExecuteRequested:return Cv(e,{isExecuting:!0,executeMethodId:t.meta&&t.meta.methodId});case Fm.ExecuteFailed:case Fm.ExecuteSucceeded:return Cv(e,{isExecuting:!1,executeMethodId:void 0});case Fm.FinalizeRequested:return Cv(e,{isFinalizing:!0,finalizeMethodId:t.meta&&t.meta.methodId});case Fm.FinalizeFailed:case Fm.FinalizeSucceeded:return Cv(e,{isFinalizing:!1,finalizeMethodId:void 0});case Fm.WidgetInteractionStarted:return Cv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Fm.WidgetInteractionFinished:case Fm.WidgetInteractionFailed:return Cv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const Wf={data:{}};function Yf(e=Wf,t){return d({data:Kf})(e,t)}function Kf(e=Wf.data,t){return t.type===tg.UpdatePaymentProviderCustomer?Cv(e,t.payload):e}const Jf={data:[],errors:{},statuses:{}};function Zf(e=Jf,t){return d({data:Xf,errors:c(eS,pv),meta:Qf,statuses:tS})(e,t)}function Xf(e=Jf.data,t){return t.type===kg.LoadInstrumentsSucceeded?_v(e,t.payload&&t.payload.vaultedInstruments||[]):e}function Qf(e,t){switch(t.type){case kg.LoadInstrumentsSucceeded:case kg.DeleteInstrumentSucceeded:return Cv(e,t.meta);default:return e}}function eS(e=Jf.errors,t){switch(t.type){case kg.LoadInstrumentsRequested:case kg.LoadInstrumentsSucceeded:return gv(e,"loadError",void 0);case kg.DeleteInstrumentRequested:case kg.DeleteInstrumentSucceeded:return Cv(e,{deleteError:void 0,failedInstrument:void 0});case kg.LoadInstrumentsFailed:return gv(e,"loadError",t.payload);case kg.DeleteInstrumentFailed:return Cv(e,{deleteError:t.payload,failedInstrument:t.meta.instrumentId});default:return e}}function tS(e=Jf.statuses,t){switch(t.type){case kg.LoadInstrumentsRequested:return gv(e,"isLoading",!0);case kg.DeleteInstrumentRequested:return Cv(e,{isDeleting:!0,deletingInstrument:t.meta.instrumentId});case kg.LoadInstrumentsSucceeded:case kg.LoadInstrumentsFailed:return gv(e,"isLoading",!1);case kg.DeleteInstrumentSucceeded:case kg.DeleteInstrumentFailed:return Cv(e,{isDeleting:!1,deletingInstrument:void 0});default:return e}}const iS={data:{}};function nS(e=iS,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:rS})})(e,t):e}function rS(e,t){switch(t.type){case ig.InitializeRemoteBillingSucceeded:return gv(e,"billing",t.payload&&t.payload.billing);case ig.InitializeRemoteShippingSucceeded:return gv(e,"shipping",t.payload&&t.payload.shipping);case ig.LoadRemoteSettingsSucceeded:return gv(e,"settings",t.payload);case ig.UpdateRemoteCheckout:return Cv(e,t.payload);default:return e}}const oS={errors:{updateShippingOptionError:{},updateError:{},deleteError:{}},statuses:{isUpdating:{},isUpdatingShippingOption:{},isDeleting:{}}};function aS(e=oS,t){return d({data:sS,errors:c(dS,pv),statuses:cS})(e,t)}function sS(e,t){var i,n;switch(t.type){case Vt.LoadCheckoutSucceeded:case cg.LoadShippingOptionsSucceeded:case cg.CreateConsignmentsSucceeded:case cg.UpdateConsignmentSucceeded:case cg.DeleteConsignmentSucceeded:case cg.UpdateShippingOptionSucceeded:case Pt.ApplyCouponSucceeded:case Pt.RemoveCouponSucceeded:return _v(e,t.payload&&t.payload.consignments);case Dt.SignOutCustomerSucceeded:return _v(e,[]);case Gt.HydrateInitialState:return _v(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.consignments);default:return e}}function dS(e=oS.errors,t){switch(t.type){case Vt.LoadCheckoutRequested:case Vt.LoadCheckoutSucceeded:case cg.LoadShippingOptionsSucceeded:case cg.LoadShippingOptionsRequested:return gv(e,"loadError",void 0);case Vt.LoadCheckoutFailed:case cg.LoadShippingOptionsFailed:return gv(e,"loadError",t.payload);case cg.CreateConsignmentsRequested:case cg.CreateConsignmentsSucceeded:return gv(e,"createError",void 0);case cg.CreateConsignmentsFailed:return gv(e,"createError",t.payload);case cg.UpdateConsignmentSucceeded:case cg.UpdateConsignmentRequested:return t.meta?Cv(e,{updateError:{[t.meta.id]:void 0}}):e;case cg.UpdateConsignmentFailed:return t.meta?Cv(e,{updateError:{[t.meta.id]:t.payload}}):e;case cg.DeleteConsignmentSucceeded:case cg.DeleteConsignmentRequested:return t.meta?Cv(e,{deleteError:{[t.meta.id]:void 0}}):e;case cg.DeleteConsignmentFailed:return t.meta?Cv(e,{deleteError:{[t.meta.id]:t.payload}}):e;case cg.UpdateShippingOptionRequested:case cg.UpdateShippingOptionSucceeded:return t.meta?Cv(e,{updateShippingOptionError:{[t.meta.id]:void 0}}):e;case cg.UpdateShippingOptionFailed:return t.meta?Cv(e,{updateShippingOptionError:{[t.meta.id]:t.payload}}):e;default:return e}}function cS(e=oS.statuses,t){switch(t.type){case Vt.LoadCheckoutRequested:return gv(e,"isLoading",!0);case cg.LoadShippingOptionsRequested:return gv(e,"isLoadingShippingOptions",!0);case Vt.LoadCheckoutSucceeded:case Vt.LoadCheckoutFailed:return gv(e,"isLoading",!1);case cg.LoadShippingOptionsSucceeded:case cg.LoadShippingOptionsFailed:return gv(e,"isLoadingShippingOptions",!1);case cg.CreateConsignmentsRequested:return gv(e,"isCreating",!0);case cg.CreateConsignmentsSucceeded:case cg.CreateConsignmentsFailed:return gv(e,"isCreating",!1);case cg.UpdateConsignmentRequested:return t.meta?Cv(e,{isUpdating:{[t.meta.id]:!0}}):e;case cg.UpdateConsignmentSucceeded:case cg.UpdateConsignmentFailed:return t.meta?Cv(e,{isUpdating:{[t.meta.id]:!1}}):e;case cg.DeleteConsignmentRequested:return t.meta?Cv(e,{isDeleting:{[t.meta.id]:!0}}):e;case cg.DeleteConsignmentSucceeded:case cg.DeleteConsignmentFailed:return t.meta?Cv(e,{isDeleting:{[t.meta.id]:!1}}):e;case cg.UpdateShippingOptionRequested:return t.meta?Cv(e,{isUpdatingShippingOption:{[t.meta.id]:!0}}):e;case cg.UpdateShippingOptionSucceeded:case cg.UpdateShippingOptionFailed:return t.meta?Cv(e,{isUpdatingShippingOption:{[t.meta.id]:!1}}):e;default:return e}}function lS(e,t){const i={};return Object.keys(e).forEach(n=>{const r=e[n],o=t?`${t}.${n}`:n;"object"==typeof r?Object.assign(i,lS(r,o)):i[o]=r}),i}function uS(e){return Object.keys(e).sort().reduce((t,i)=>Object.assign(Object.assign({},t),{[i]:e[i]}),{})}const hS={errors:{},statuses:{}};function pS(e=hS,t){return d({data:mS,errors:c(yS,pv),statuses:gS})(e,t)}function mS(e,t){if(t.type!==Fg.LoadPickupOptionsSucceeded)return e;if(t.meta){const i=uS(lS({consignmentId:t.meta.consignmentId,searchArea:t.meta.searchArea}));return gv(e,btoa(`${JSON.stringify(i)}`),t.payload)}}function yS(e=hS.errors,t){switch(t.type){case Fg.LoadPickupOptionsRequested:case Fg.LoadPickupOptionsSucceeded:return gv(e,"loadError",void 0);case Fg.LoadPickupOptionsFailed:return gv(e,"loadError",t.payload);default:return e}}function gS(e=hS.statuses,t){switch(t.type){case Fg.LoadPickupOptionsRequested:return gv(e,"isLoading",!0);case Fg.LoadPickupOptionsSucceeded:case Fg.LoadPickupOptionsFailed:return gv(e,"isLoading",!1);default:return e}}const vS={errors:{},statuses:{}};function fS(e=vS,t){return d({data:SS,errors:c(wS,pv),statuses:IS})(e,t)}function SS(e,t){return t.type===yg.LoadShippingCountriesSucceeded?_v(e,t.payload):e}function wS(e=vS.errors,t){switch(t.type){case yg.LoadShippingCountriesRequested:case yg.LoadShippingCountriesSucceeded:return gv(e,"loadError",void 0);case yg.LoadShippingCountriesFailed:return gv(e,"loadError",t.payload);default:return e}}function IS(e=vS.statuses,t){switch(t.type){case yg.LoadShippingCountriesRequested:return gv(e,"isLoading",!0);case yg.LoadShippingCountriesSucceeded:case yg.LoadShippingCountriesFailed:return gv(e,"isLoading",!1);default:return e}}const _S={data:{},errors:{},statuses:{}};function CS(e=_S,t){return d({data:bS,errors:c(PS,pv),statuses:OS})(e,t)}function bS(e=_S.data,t){switch(t.type){case Rg.InitializeSucceeded:return Cv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Rg.DeinitializeSucceeded:return Cv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function PS(e=_S.errors,t){switch(t.type){case Rg.InitializeRequested:case Rg.InitializeSucceeded:return Cv(e,{initializeError:void 0,initializeMethodId:void 0});case Rg.InitializeFailed:return Cv(e,{initializeError:t.payload,initializeMethodId:t.meta&&t.meta.methodId});case Rg.DeinitializeRequested:case Rg.DeinitializeSucceeded:return Cv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Rg.DeinitializeFailed:return Cv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Rg.UpdateAddressRequested:case Rg.UpdateAddressSucceeded:return Cv(e,{updateAddressError:void 0,updateAddressMethodId:void 0});case Rg.UpdateAddressFailed:return Cv(e,{updateAddressError:t.payload,updateAddressMethodId:t.meta&&t.meta.methodId});case Rg.SelectOptionRequested:case Rg.SelectOptionSucceeded:return Cv(e,{selectOptionError:void 0,selectOptionMethodId:void 0});case Rg.SelectOptionFailed:return Cv(e,{selectOptionError:t.payload,selectOptionMethodId:t.meta&&t.meta.methodId});case Rg.WidgetInteractionStarted:case Rg.WidgetInteractionFinished:return Cv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Rg.WidgetInteractionFailed:return Cv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta&&t.meta.methodId});default:return e}}function OS(e=_S.statuses,t){switch(t.type){case Rg.InitializeRequested:return Cv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Rg.InitializeFailed:case Rg.InitializeSucceeded:return Cv(e,{isInitializing:!1,initializeMethodId:void 0});case Rg.DeinitializeRequested:return Cv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Rg.DeinitializeFailed:case Rg.DeinitializeSucceeded:return Cv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Rg.UpdateAddressRequested:return Cv(e,{isUpdatingAddress:!0,updateAddressMethodId:t.meta&&t.meta.methodId});case Rg.UpdateAddressFailed:case Rg.UpdateAddressSucceeded:return Cv(e,{isUpdatingAddress:!1,updateAddressMethodId:void 0});case Rg.SelectOptionRequested:return Cv(e,{isSelectingOption:!0,selectOptionMethodId:t.meta&&t.meta.methodId});case Rg.SelectOptionFailed:case Rg.SelectOptionSucceeded:return Cv(e,{isSelectingOption:!1,selectOptionMethodId:void 0});case Rg.WidgetInteractionStarted:return Cv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta&&t.meta.methodId});case Rg.WidgetInteractionFinished:case Rg.WidgetInteractionFailed:return Cv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const ES={errors:{},statuses:{}};function AS(e=ES,t){return d({data:TS,errors:c(kS,pv),statuses:DS})(e,t)}function TS(e,t){return t.type===Xg.SendSignInEmailSucceeded?Cv(e,t.payload):e}function kS(e=ES.errors,t){switch(t.type){case Xg.SendSignInEmailRequested:case Xg.SendSignInEmailSucceeded:return gv(e,"sendError",void 0);case Xg.SendSignInEmailFailed:return gv(e,"sendError",t.payload);default:return e}}function DS(e=ES.statuses,t){switch(t.type){case Xg.SendSignInEmailRequested:return gv(e,"isSending",!0);case Xg.SendSignInEmailFailed:case Xg.SendSignInEmailSucceeded:return gv(e,"isSending",!1);default:return e}}const MS={errors:{},statuses:{}};function zS(e=MS,t){return d({errors:c(NS,pv),statuses:xS})(e,t)}function NS(e=MS.errors,t){switch(t.type){case gg.ApplyStoreCreditRequested:case gg.ApplyStoreCreditSucceeded:return gv(e,"applyError",void 0);case gg.ApplyStoreCreditFailed:return gv(e,"applyError",t.payload);default:return e}}function xS(e=MS.statuses,t){switch(t.type){case gg.ApplyStoreCreditRequested:return gv(e,"isApplying",!0);case gg.ApplyStoreCreditSucceeded:case gg.ApplyStoreCreditFailed:return gv(e,"isApplying",!1);default:return e}}const FS={errors:{},statuses:{}};function RS(e=FS,t){return d({errors:c(LS,pv),statuses:BS})(e,t)}function LS(e=FS.errors,t){switch(t.type){case Sg.UpdateSubscriptionsRequested:case Sg.UpdateSubscriptionsSucceeded:return gv(e,"updateError",void 0);case Sg.UpdateSubscriptionsFailed:return gv(e,"updateError",t.payload);default:return e}}function BS(e=FS.statuses,t){switch(t.type){case Sg.UpdateSubscriptionsRequested:return gv(e,"isUpdating",!0);case Sg.UpdateSubscriptionsFailed:case Sg.UpdateSubscriptionsSucceeded:return gv(e,"isUpdating",!1);default:return e}}const jS={errors:{},statuses:{}};function US(e=jS,t){return d({data:qS,errors:c(VS,pv),statuses:GS})(e,t)}function qS(e,t){var i;switch(t.type){case Vt.LoadCheckoutSucceeded:case Vt.UpdateCheckoutSucceeded:case gg.ApplyStoreCreditSucceeded:case Ye.UpdateBillingAddressSucceeded:case Pt.ApplyCouponSucceeded:case Pt.RemoveCouponSucceeded:case cg.CreateConsignmentsSucceeded:case cg.UpdateConsignmentSucceeded:case cg.DeleteConsignmentSucceeded:case cg.UpdateShippingOptionSucceeded:case cg.LoadShippingOptionsSucceeded:case Tt.ApplyGiftCertificateSucceeded:case Tt.RemoveGiftCertificateSucceeded:case ii.VerifyCheckoutSucceeded:return Cv(e,G(t.payload,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));case wm.SubmitOrderSucceeded:return gv(e,"orderId",t.payload&&t.payload.order.orderId);case Gt.HydrateInitialState:return Cv(e,G(null===(i=t.payload)||void 0===i?void 0:i.checkout,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));default:return e}}function VS(e=jS.errors,t){switch(t.type){case Vt.LoadCheckoutRequested:case Vt.LoadCheckoutSucceeded:return gv(e,"loadError",void 0);case Vt.LoadCheckoutFailed:return gv(e,"loadError",t.payload);case Vt.UpdateCheckoutRequested:case Vt.UpdateCheckoutSucceeded:return gv(e,"updateError",void 0);case Vt.UpdateCheckoutFailed:return gv(e,"updateError",t.payload);default:return e}}function GS(e=jS.statuses,t){switch(t.type){case Vt.LoadCheckoutRequested:return gv(e,"isLoading",!0);case Vt.LoadCheckoutFailed:case Vt.LoadCheckoutSucceeded:return gv(e,"isLoading",!1);case Vt.UpdateCheckoutRequested:return gv(e,"isUpdating",!0);case Vt.UpdateCheckoutFailed:case Vt.UpdateCheckoutSucceeded:return gv(e,"isUpdating",!1);case ii.ExecuteRequested:return gv(e,"isExecutingSpamCheck",!0);case ii.ExecuteFailed:case ii.ExecuteSucceeded:return gv(e,"isExecutingSpamCheck",!1);default:return e}}function HS(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}function $S(e){return function(e){const t=Object.create(e);return function(e,t){let i=Object.getPrototypeOf(e);for(;i;)t(i),i=Object.getPrototypeOf(i)}(e,i=>{Object.getOwnPropertyNames(i).forEach(i=>{"constructor"!==i&&"function"==typeof t[i]&&"_"!==i.charAt(0)&&(t[i]=((e,t)=>(...i)=>p(e[t].call(e,...i)))(e,i))})}),t}(e)}const WS={"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"},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 YS(e){return Y({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},b)}const KS={errors:{},statuses:{}};function JS(){const e=function(){const e=av(e=>e.data,e=>()=>e),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingBillingAddress))),i=av(e=>e.errors.updateError,e=>()=>e),n=av(e=>e.errors.continueAsGuestError,e=>()=>e),r=av(e=>e.errors.loadError,e=>()=>e),o=av(e=>!!e.statuses.isUpdating,e=>()=>e),a=av(e=>!!e.statuses.isContinuingAsGuest,e=>()=>e),s=av(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((d=vv)=>({getBillingAddress:e(d),getBillingAddressOrThrow:t(d),getUpdateError:i(d),getContinueAsGuestError:n(d),getLoadError:r(d),isUpdating:o(d),isContinuingAsGuest:a(d),isLoading:s(d)}))}(),t=function(){const e=av(e=>e.data,e=>()=>e),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingCart))),i=av(e=>e.errors.loadError,e=>()=>e),n=av(e=>!!e.statuses.isLoading,e=>()=>e),r=av(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.locale},e=>()=>e);return Oe((o=bv)=>({getCart:e(o),getCartOrThrow:t(o),getLoadError:i(o),isLoading:n(o),getLocale:r(o)}))}(),i=function(){const e=av(e=>e,e=>()=>e),t=av(e=>e.statuses,e=>Pe(t=>{if(t){const i=e[t];return!0===(i&&i.isInitializing)}return Z(e,{isInitializing:!0})})),i=av(e=>e.data,e=>Pe((t,i)=>{const n=e[t];return!!n&&(i?!0===n.initializedContainers[i]:Z(n.initializedContainers,e=>!0===e))})),n=av(e=>e.statuses,e=>Pe(t=>{if(t){const i=e[t];return!0===(i&&i.isDeinitializing)}return Z(e,{isDeinitializing:!0})})),r=av(e=>e.errors,e=>Pe(t=>{const i=t?e[t]:S(ne(e),e=>!(!e||!e.initializeError));return i&&i.initializeError})),o=av(e=>e.errors,e=>Pe(t=>{const i=t?e[t]:S(ne(e),e=>!(!e||!e.deinitializeError));return i&&i.deinitializeError}));return Oe((a=kv)=>({getState:e(a),isInitializing:t(a),isInitialized:i(a),isDeinitializing:n(a),getInitializeError:r(a),getDeinitializeError:o(a)}))}(),n=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.data,e=>t=>{if(!e)return;const{flashMessages:i}=e.context;return i?void 0!==t?i.filter(({type:e})=>t===e):i:void 0}),i=av(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),n=av(i,e=>()=>HS(e(),()=>new Xe(We.MissingCheckoutConfig))),r=av(e=>e.data&&e.data.context,e=>()=>e),o=av(e=>e.meta&&e.meta.externalSource,e=>()=>e),a=av(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.host},e=>()=>e),s=av(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.locale},e=>()=>e),d=av(e=>e.meta&&e.meta.variantIdentificationToken,e=>()=>e),c=av(e=>e.errors.loadError,e=>()=>e),l=av(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((u=Lv,h)=>({getConfig:e(u),getFlashMessages:t(u),getStoreConfig:i(u,{formState:h}),getStoreConfigOrThrow:n(u,{formState:h}),getContextConfig:r(u),getExternalSource:o(u),getHost:a(u),getLocale:s(u),getVariantIdentificationToken:d(u),getLoadError:c(u),isLoading:l(u)}))}(),r=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.errors.loadError,e=>()=>e),i=av(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((n=wf)=>({getCountries:e(n),getLoadError:t(n),isLoading:i(n)}))}(),o=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.errors.removeCouponError,e=>()=>e),i=av(e=>e.errors.applyCouponError,e=>()=>e),n=av(e=>!!e.statuses.isApplyingCoupon,e=>()=>e),r=av(e=>!!e.statuses.isRemovingCoupon,e=>()=>e);return Oe((o=Vv)=>({getCoupons:e(o),getRemoveError:t(o),getApplyError:i(o),isApplying:n(o),isRemoving:r(o)}))}(),a=function(){const e=av(e=>e.data,e=>()=>e),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingCustomer))),i=av(e=>e.errors.createError,e=>()=>e),n=av(e=>!!e.statuses.isCreating,e=>()=>e),r=av(e=>e.errors.createAddressError,e=>()=>e),o=av(e=>!!e.statuses.isCreatingAddress,e=>()=>e);return Oe((a=Qv)=>({getCustomer:e(a),getCustomerOrThrow:t(a),getCreateAccountError:i(a),isCreatingCustomerAccount:n(a),getCreateAddressError:r(a),isCreatingCustomerAddress:o(a)}))}(),s=function(){const e=av(e=>e.errors.signInMethodId,e=>e.errors.signInError,(e,t)=>i=>{if(!i||e===i)return t}),t=av(e=>e.errors.signOutMethodId,e=>e.errors.signOutError,(e,t)=>i=>{if(!i||e===i)return t}),i=av(e=>e.errors.executePaymentMethodCheckoutMethodId,e=>e.errors.executePaymentMethodCheckoutError,(e,t)=>i=>{if(!i||e===i)return t}),n=av(e=>e.errors.initializeMethodId,e=>e.errors.initializeErrors,(e,t)=>i=>{if(e&&t)return i?t[i]:t[e]}),r=av(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>i=>{if(!i||e===i)return t}),o=av(e=>e.statuses.signInMethodId,e=>e.statuses.isSigningIn,(e,t)=>i=>!(i&&e!==i||!t)),a=av(e=>e.statuses.signOutMethodId,e=>e.statuses.isSigningOut,(e,t)=>i=>!(i&&e!==i||!t)),s=av(e=>e.statuses.executePaymentMethodCheckoutMethodId,e=>e.statuses.isExecutingPaymentMethodCheckout,(e,t)=>i=>!(i&&e!==i||!t)),d=av(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>i=>!(i&&e!==i||!t)),c=av(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),l=av(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>i=>!(i&&e!==i||!t));return Oe((u=of)=>({getSignInError:e(u),getSignOutError:t(u),getExecutePaymentMethodCheckoutError:i(u),getInitializeError:n(u),getWidgetInteractionError:r(u),isSigningIn:o(u),isSigningOut:a(u),isExecutingPaymentMethodCheckout:s(u),isInitializing:d(u),isInitialized:c(u),isWidgetInteracting:l(u)}))}(),d=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.errors.removeGiftCertificateError,e=>()=>e),i=av(e=>e.errors.applyGiftCertificateError,e=>()=>e),n=av(e=>!!e.statuses.isApplyingGiftCertificate,e=>()=>e),r=av(e=>!!e.statuses.isRemovingGiftCertificate,e=>()=>e);return Oe((o=Yv)=>({getGiftCertificates:e(o),getRemoveError:t(o),getApplyError:i(o),isApplying:n(o),isRemoving:r(o)}))}(),c=function(){const e=av(e=>e.data,e=>t=>{if(!e)return;const i=t.gateway?`${t.gateway}.${t.id}`:t.id,n=WS[i];return n?f(e,n):[]}),t=av(e=>e.data,(e=[])=>t=>{const i=ne(WS);return e.find(e=>e.bigpayToken===t&&"card"===e.type&&i.some(t=>T(e,t)))}),i=av(t,e=>t=>HS(e(t),()=>new Xe(We.MissingPaymentInstrument))),n=av(e=>e.data,e=>()=>{if(e)return I(WS,t=>f(e,e=>T(e,t)))}),r=av(e=>e.meta,e=>()=>e),o=av(e=>e.errors.loadError,e=>()=>e),a=av(e=>e.errors.failedInstrument,e=>e.errors.deleteError,(e,t)=>i=>{if(!i||e===i)return t}),s=av(e=>e.statuses.isLoading,e=>()=>!!e),d=av(e=>e.statuses.deletingInstrument,e=>e.statuses.isDeleting,(e,t)=>i=>!(i&&e!==i||!t));return Oe((c=Jf)=>({getCardInstrument:t(c),getCardInstrumentOrThrow:i(c),getInstruments:n(c),getInstrumentsByPaymentMethod:e(c),getInstrumentsMeta:r(c),getLoadError:o(c),getDeleteError:a(c),isLoading:s(c),isDeleting:d(c)}))}(),l=function(){const e=av(e=>e.data,e=>(t=[],i)=>{const n=S(t,{code:i});return(e?e.shippingAddress:[]).map(e=>o(e,t,n))}),t=av(e=>e.data,e=>(t=[],i)=>{const n=S(t,{code:i});return(e?e.billingAddress:[]).map(e=>o(e,t,n))}),i=av(e=>e.data,e=>()=>e?e.customerAccount:[]),n=av(e=>e.errors.loadError,e=>()=>e),r=av(e=>!!e.statuses.isLoading,e=>()=>e);function o(e,t,i){return"countryCode"===e.name?function(e,t=[],i){if(!t.length)return e;const{code:n=""}=i||{},r=t.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{options:{items:r},default:n,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,t,i):"stateOrProvince"===e.name?function(e,t){const{subdivisions:i=[],requiresState:n}=t||{};if(!i.length)return Object.assign(Object.assign({},e),{required:null!=n&&n});const r=i.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{name:"stateOrProvinceCode",options:{items:r},required:null==n||n,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,i):"postalCode"===e.name?function(e,t){const{hasPostalCodes:i=[]}=t||{};return void 0===i?e:Object.assign(Object.assign({},e),{required:Boolean(i)})}(e,i):e}return Oe((o=yf)=>({getShippingAddressFields:e(o),getBillingAddressFields:t(o),getCustomerAccountFields:i(o),getLoadError:n(o),isLoading:r(o)}))}(),u=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.meta,e=>()=>e),i=av(e=>e.data,e=>(t,i)=>S(e,i?{id:t,gateway:i}:{id:t})),n=av(i,e=>(t,i)=>HS(e(t,i),()=>new Xe(We.MissingPaymentMethod))),r=av(e=>e.errors.loadError,e=>()=>e),o=av(e=>e.errors.loadMethodId,e=>e.errors.loadMethodError,(e,t)=>i=>{if(!i||e===i)return t}),a=av(e=>e.statuses.isLoading,e=>()=>!!e),s=av(e=>e.statuses.loadMethodId,e=>e.statuses.isLoadingMethod,(e,t)=>i=>!(i&&e!==i||!t));return Oe((d=Ff)=>({getPaymentMethods:e(d),getPaymentMethodsMeta:t(d),getPaymentMethod:i(d),getPaymentMethodOrThrow:n(d),getLoadError:r(d),getLoadMethodError:o(d),isLoading:a(d),isLoadingMethod:s(d)}))}(),h=function(){const e=av(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>i=>{if(!i||e===i)return t}),t=av(e=>e.errors.executeMethodId,e=>e.errors.executeError,(e,t)=>i=>{if(!i||e===i)return t}),i=av(e=>e.errors.finalizeMethodId,e=>e.errors.finalizeError,(e,t)=>i=>{if(!i||e===i)return t}),n=av(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>i=>{if(!i||e===i)return t}),r=av(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>i=>!(i&&e!==i||!t)),o=av(e=>e.data,e=>t=>{const i=t.gatewayId?`${t.methodId}.${t.gatewayId}`:t.methodId;return!(!e[i]||!e[i].isInitialized)}),a=av(e=>e.statuses.executeMethodId,e=>e.statuses.isExecuting,(e,t)=>i=>!(i&&e!==i||!t)),s=av(e=>e.statuses.finalizeMethodId,e=>e.statuses.isFinalizing,(e,t)=>i=>!(i&&e!==i||!t)),d=av(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>i=>!(i&&e!==i||!t));return Oe((c=qf)=>({getInitializeError:e(c),getExecuteError:t(c),getFinalizeError:i(c),getWidgetInteractingError:n(c),isInitializing:r(c),isInitialized:o(c),isExecuting:a(c),isFinalizing:s(c),isWidgetInteracting:d(c)}))}(),p=function(){const e=av(e=>e.data,e=>(t,i)=>{if(!e)return;const n=uS(lS({consignmentId:t,searchArea:i})),r=btoa(`${JSON.stringify(n)}`);return e[r]}),t=av(e=>e.errors.loadError,e=>()=>e),i=av(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((n=hS)=>({getPickupOptions:e(n),getLoadError:t(n),isLoading:i(n)}))}(),m=function(){const e=av(e=>e.data,e=>()=>e),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingPaymentProviderCustomer)));return Oe((i=Wf)=>({getPaymentProviderCustomer:e(i),getPaymentProviderCustomerOrThrow:t(i)}))}(),y=function(){const e=av(e=>e.data,e=>t=>e[t]);return Oe((t=iS)=>({getCheckout:e(t)}))}(),g=function(){const e=av(e=>e.data,e=>()=>{const t=null==e?void 0:e.find(e=>!e.selectedPickupOption);return null==t?void 0:t.shippingAddress}),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingShippingAddress))),i=av(e=>e.data,e=>()=>{const t=null==e?void 0:e.filter(e=>!e.selectedPickupOption);return t?t.map(e=>e.shippingAddress):[]}),n=av(i,e=>()=>HS(e(),()=>new Xe(We.MissingShippingAddress)));return Oe((r=oS)=>({getShippingAddress:e(r),getShippingAddressOrThrow:t(r),getShippingAddresses:i(r),getShippingAddressesOrThrow:n(r)}))}(),v=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.errors.loadError,e=>()=>e),i=av(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((n=vS)=>({getShippingCountries:e(n),getLoadError:t(n),isLoading:i(n)}))}(),w=function(){const e=av(e=>e.errors.updateAddressMethodId,e=>e.errors.updateAddressError,(e,t)=>i=>{if(!i||e===i)return t}),t=av(e=>e.errors.selectOptionMethodId,e=>e.errors.selectOptionError,(e,t)=>i=>{if(!i||e===i)return t}),i=av(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>i=>{if(!i||e===i)return t}),n=av(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>i=>{if(!i||e===i)return t}),r=av(e=>e.statuses.updateAddressMethodId,e=>e.statuses.isUpdatingAddress,(e,t)=>i=>!(i&&e!==i||!t)),o=av(e=>e.statuses.selectOptionMethodId,e=>e.statuses.isSelectingOption,(e,t)=>i=>!(i&&e!==i||!t)),a=av(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>i=>!(i&&e!==i||!t)),s=av(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),d=av(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>i=>!(i&&e!==i||!t));return Oe((c=_S)=>({getUpdateAddressError:e(c),getSelectOptionError:t(c),getInitializeError:i(c),getWidgetInteractionError:n(c),isUpdatingAddress:r(c),isSelectingOption:o(c),isInitializing:a(c),isInitialized:s(c),isWidgetInteracting:d(c)}))}(),_=function(){const e=av(e=>e.data,e=>()=>e),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingConsignments))),i=av(e=>e.data,e=>t=>{if(e&&e.length)return S(e,{id:t})}),n=av(e=>e.data,e=>t=>{if(e&&e.length)return S(e,e=>{return i=e.shippingAddress,n=t,A(YS(i),YS(n));var i,n})}),r=av(e=>e.data,e=>()=>{if(e&&e.length)return e[0].selectedShippingOption}),o=av(e=>e.errors.loadError,e=>()=>e),a=av(e=>e.errors.createError,e=>()=>e),s=av(e=>e.errors.loadShippingOptionsError,e=>()=>e),d=av(e,(e,{cart:t})=>t.getCart,(e,t)=>()=>{const i=t();if(!i)return[];const n=(e()||[]).reduce((e,t)=>e.concat(t.lineItemIds),[]);return(i.lineItems.physicalItems||[]).filter(e=>n.indexOf(e.id)<0)}),c=av(e=>e.errors.updateError,e=>t=>t?e[t]:S(e)),l=av(e=>e.errors.deleteError,e=>t=>t?e[t]:S(e)),u=av(n,c,a,(e,t,i)=>n=>{const r=e(n);return r?t(r.id):i()}),h=av(e=>e.errors.updateShippingOptionError,e=>t=>t?e[t]:S(e)),p=av(e=>e.statuses.isLoading,e=>()=>!0===e),m=av(e=>e.statuses.isLoadingShippingOptions,e=>()=>!0===e),y=av(e=>e.statuses.isCreating,e=>()=>!0===e),g=av(e=>e.statuses.isUpdating,e=>t=>t?!0===e[t]:!0===S(e)),v=av(e=>e.statuses.isDeleting,e=>t=>t?!0===e[t]:!0===S(e)),f=av(n,g,y,(e,t,i)=>n=>{const r=e(n);return r?t(r.id):i()}),w=av(e=>e.statuses.isUpdatingShippingOption,e=>t=>t?!0===e[t]:!0===S(e));return Oe((S=oS,I)=>({getConsignments:e(S),getConsignmentsOrThrow:t(S),getConsignmentById:i(S),getConsignmentByAddress:n(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:v(S),isAssigningItems:f(S),isUpdatingShippingOption:w(S)}))}(),C=function(){const e=av(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,i,n,r,o,a)=>()=>{const s=t(),d=i(),c=n(),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=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingCheckout))),i=av(e,e=>t=>{const i=e();if(!i)return;const n=i.grandTotal||0,r=i.customer.storeCredit||0;return t?Math.max(n-r,0):i.outstandingBalance}),n=av(e=>e.errors.loadError,e=>()=>e),r=av(e=>e.errors.updateError,e=>()=>e),o=av(e=>e.statuses.isExecutingSpamCheck,e=>()=>!0===e),a=av(e=>e.statuses.isLoading,e=>()=>!0===e),s=av(e=>e.statuses.isUpdating,e=>()=>!0===e);return Oe((d=jS,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:i(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getLoadError:n(d),getUpdateError:r(d),isExecutingSpamCheck:o(d),isLoading:a(d),isUpdating:s(d)}))}(),b=function(){const e=av(e=>e.data,(e,{billingAddress:t})=>t.getOrderBillingAddress(),(e,{coupons:t})=>t.getCoupons(),(e,t,i=[])=>()=>{if(e&&t)return Object.assign(Object.assign({},e),{billingAddress:t,coupons:i})}),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingOrder))),i=av(e=>e.meta,e=>()=>e),n=av(e=>e.errors.loadError,e=>()=>e),r=av(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.payments},(e=[])=>t=>{const i=e.find(({providerId:e})=>e===t);return null==i?void 0:i.paymentId}),o=av(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((a=Pf,s,d)=>({getOrder:e(a,{billingAddress:s,coupons:d}),getOrderOrThrow:t(a,{billingAddress:s,coupons:d}),getOrderMeta:i(a),getLoadError:n(a),getPaymentId:r(a),isLoading:o(a)}))}(),P=function(){const e=av(e=>e.data,e=>()=>e);return Oe((t=Df)=>({getOrderBillingAddress:e(t)}))}(),O=function(){const e=av(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.payment}),t=av(({order:e})=>e.getOrder,e=>()=>{const t=e();return S(t&&t.payments,({providerId:e})=>"giftcertificate"!==e&&"storecredit"!==e)}),i=av(({checkout:e})=>e.getCheckout,e=>()=>{const t=e();return S(t&&t.payments,({providerType:e})=>"PAYMENT_TYPE_HOSTED"===e)}),n=av(e,i,t,(e,t,i)=>()=>{const n=e();if(n&&n.id)return{providerId:n.id,gatewayId:n.gateway};const r=t()||i();return r&&r.providerId?{providerId:r.providerId,gatewayId:r.gatewayId}:void 0}),r=av(n,e=>()=>HS(e(),()=>new Xe(We.MissingPaymentId))),o=av(e,i,t,(e,t,i)=>()=>{const n=e();if(n&&n.status)return n.status.replace("PAYMENT_STATUS_","");const r=t()||i();return r?r.detail.step:void 0}),a=av(o,e=>()=>HS(e(),()=>new Xe(We.MissingPaymentStatus))),s=av(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.token}),d=av(s,e=>()=>HS(e(),()=>new Xe(We.MissingPaymentToken))),c=av(e,e=>()=>{const t=e();return t&&t.redirectUrl}),l=av(c,e=>()=>HS(e(),()=>new Xe(We.MissingPaymentRedirectUrl))),u=av(({checkout:e})=>e.getOutstandingBalance,e=>(t=!1)=>{const i=e(t);return!!i&&i>0}),h=av(o,e=>t=>!(!t||!t.nonce)||"ACKNOWLEDGE"===e()||e()===Ny);return Oe((e,t)=>({getPaymentId:n({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})}))}(),E=function(){const e=av(e=>e.errors.applyError,e=>()=>e),t=av(e=>!!e.statuses.isApplying,e=>()=>e);return Oe((i=KS)=>({getApplyError:e(i),isApplying:t(i)}))}(),k=function(){const e=av(e=>e.errors.updateError,e=>()=>e),t=av(e=>!!e.statuses.isUpdating,e=>()=>e);return Oe((i=FS)=>({getUpdateError:e(i),isUpdating:t(i)}))}(),D=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.errors.sendError,e=>()=>e),i=av(e=>!!e.statuses.isSending,e=>()=>e);return Oe((n=ES)=>({getEmail:e(n),getSendError:t(n),isSending:i(n)}))}(),M=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.data,e=>t=>null==e?void 0:e.find(e=>e.region===t)),i=av(e=>e.errors.loadError,e=>()=>e),n=av(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((r=lf)=>({getExtensions:e(r),getExtensionByRegion:t(r),getLoadError:i(r),isLoading:n(r)}))}();return(f,S={})=>{const I=e(f.billingAddress),A=t(f.cart),T=i(f.checkoutButton),z=r(f.countries),N=o(f.coupons),x=a(f.customer),F=s(f.customerStrategies),R=M(f.extensions),L=l(f.formFields),B=d(f.giftCertificates),j=c(f.instruments),U=P(f.orderBillingAddress),q=u(f.paymentMethods),V=m(f.paymentProviderCustomer),G=h(f.paymentStrategies),H=p(f.pickupOptions),$=y(f.remoteCheckout),W=g(f.consignments),Y=v(f.shippingCountries),K=w(f.shippingStrategies),J=k(f.subscriptions),Z=E(f.storeCredit),X=D(f.signInEmail),Q=_(f.consignments,A),ee=C(f.checkout,I,A,Q,N,x,B),te=b(f.order,U,N),ie=O(ee,te),ne={billingAddress:I,cart:A,checkout:ee,checkoutButton:T,config:n(f.config,f.formFields),consignments:Q,countries:z,coupons:N,customer:x,customerStrategies:F,extensions:R,form:L,giftCertificates:B,instruments:j,order:te,orderBillingAddress:U,payment:ie,paymentMethods:q,paymentProviderCustomer:V,paymentStrategies:G,pickupOptions:H,remoteCheckout:$,shippingAddress:W,shippingCountries:Y,shippingStrategies:K,signInEmail:X,subscriptions:J,storeCredit:Z};return S.shouldWarnMutation?function(e){return Object.keys(e).reduce((t,i)=>(t[i]=$S(e[i]),t),{})}(ne):ne}}function ZS(e={},t){const i=(o=function(){const e=new uv;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 dv(e,t))}),e.register("invalid_payment_provider",e=>new Jr(e)),e.register("payment_config_not_found",e=>new Jr(e)),e}(),e=>le(e).pipe(ge(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}))),n=JS(),r=d({billingAddress:fv,cart:Pv,checkout:US,checkoutButton:Nv,config:Bv,consignments:aS,countries:If,coupons:Gv,customer:ef,customerStrategies:af,extensions:uf,formFields:gf,giftCertificates:Kv,instruments:Zf,orderBillingAddress:Mf,order:Of,payment:Nf,paymentMethods:Rf,paymentStrategies:Vf,pickupOptions:pS,paymentProviderCustomer:Yf,remoteCheckout:nS,shippingCountries:fS,shippingStrategies:CS,signInEmail:AS,subscriptions:RS,storeCredit:zS});var o;return u(r,e,Object.assign({actionTransformer:i,stateTransformer:e=>n(e)},t))}function XS(e){"https:"!==document.location.protocol&>().warn("The BigCommerce Checkout SDK should not be used on a non-HTTPS page"),"production"!==ht()&>().warn("Note that the development build is not optimized. To create a production build, set process.env.NODE_ENV to `production`.");const t={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:n="",shouldWarnMutation:r=!0,errorLogger:s=new lt}=e||{},d=i({host:e&&e.host}),c=ZS({config:t},{shouldWarnMutation:r}),l=Dm(c),u=new Em(d),h=new Qt(d),p=new St(new bt(d)),m=vi(o()),y=new fi(d),g=new ui(m,y),v=new km(u,new Vm(h)),f=new Cg(new bg(d)),S=new ni(new ri(d)),w=new ti(h,p,S),I=Ng(c),_=function(e,t,i={useFallback:!1}){const{useFallback:n}=i,r=new jt(n);for(const[,i]of Object.entries(t))if(Ft(i))for(const t of i.resolveIds){const n=Rt(()=>i(e),i.resolveIds);r.register(t,n)}return r}(I,$e,{useFallback:!0}),C=function(e,t){const i=new jt;for(const[,n]of Object.entries(t))if(Ft(n))for(const t of n.resolveIds){const r=Rt(()=>n(e),n.resolveIds);i.register(t,r)}return i}(I,He),b=new zi(new Ni(d)),P=new Vi,O=new Wi(c,P),E=ct(c,function(){const e=function(){const e=av(({checkout:e})=>e.getCheckout,e=>Ag(e)),t=av(({order:e})=>e.getOrder,e=>Ag(e)),i=av(({config:e})=>e.getStoreConfig,e=>Ag(e)),n=av(({shippingAddress:e})=>e.getShippingAddress,({config:e})=>e.getContextConfig,(e,t)=>Ag(()=>{const i=e(),n=t();if(!i){if(!n||!n.geoCountryCode)return;return{firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:n.geoCountryCode}}return i})),r=av(({consignments:e})=>e.getConsignments,e=>Ag(()=>{const t=e(),i=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==i?void 0:i.availableShippingOptions})),o=av(({consignments:e})=>e.getConsignments,e=>Ag(e)),a=av(({consignments:e})=>e.getConsignments,e=>Ag(()=>{const t=e(),i=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==i?void 0:i.selectedShippingOption})),s=av(({shippingCountries:e})=>e.getShippingCountries,e=>Ag(e)),d=av(({billingAddress:e})=>e.getBillingAddress,({config:e})=>e.getContextConfig,(e,t)=>Ag(()=>{const i=e(),n=t();return(!i||ne(G(i,"shouldSaveAddress","email","id")).every(e=>!e||!e.length))&&n&&n.geoCountryCode?{id:i?i.id:"",firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",email:i?i.email:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:n.geoCountryCode}:i})),c=av(({countries:e})=>e.getCountries,e=>Ag(e)),l=av(({paymentMethods:e})=>e.getPaymentMethods,e=>Ag(e)),u=av(({paymentMethods:e})=>e.getPaymentMethod,e=>Ag(e)),h=av(({payment:e})=>e.getPaymentId,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Ag(()=>{const i=e();return i&&t(i.providerId,i.gatewayId)})),p=av(({cart:e})=>e.getCart,e=>Ag(e)),m=av(({coupons:e})=>e.getCoupons,e=>Ag(e)),y=av(({giftCertificates:e})=>e.getGiftCertificates,e=>Ag(e)),g=av(({customer:e})=>e.getCustomer,e=>Ag(e)),v=av(({signInEmail:e})=>e.getEmail,e=>Ag(e)),f=av(({payment:e})=>e.isPaymentDataRequired,e=>Ag(e)),S=av(({payment:e})=>e.isPaymentDataSubmitted,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Ag((i,n)=>e(t(i,n)))),w=av(({instruments:e})=>e.getInstruments,({instruments:e})=>e.getInstrumentsByPaymentMethod,(e,t)=>Ag(function(i){return i?t(i):e()})),I=av(({form:e})=>e.getCustomerAccountFields,e=>Ag(e)),_=av(({form:e})=>e.getBillingAddressFields,({countries:e})=>e.getCountries,(e,t)=>Ag(i=>e(t(),i))),C=av(({form:e})=>e.getShippingAddressFields,({shippingCountries:e})=>e.getShippingCountries,(e,t)=>Ag(i=>e(t(),i))),b=av(({config:e})=>e.getFlashMessages,e=>Ag(e)),P=av(({pickupOptions:e})=>e.getPickupOptions,e=>Ag(e)),O=av(({config:e})=>e.getStoreConfig,e=>Ag(()=>{const t=e();if(t)return t.checkoutSettings.checkoutUserExperienceSettings})),E=av(({extensions:e})=>e.getExtensions,e=>Ag(e)),A=av(({paymentProviderCustomer:e})=>e.getPaymentProviderCustomer,e=>Ag(e)),T=av(({extensions:e})=>e.getExtensionByRegion,e=>Ag(e));return Oe(k=>({getCheckout:e(k),getOrder:t(k),getConfig:i(k),getExtensions:E(k),getExtensionByRegion:T(k),getFlashMessages:b(k),getShippingAddress:n(k),getShippingOptions:r(k),getConsignments:o(k),getSelectedShippingOption:a(k),getShippingCountries:s(k),getBillingAddress:d(k),getBillingCountries:c(k),getPaymentMethods:l(k),getPaymentMethod:u(k),getSelectedPaymentMethod:h(k),getCart:p(k),getCoupons:m(k),getGiftCertificates:y(k),getCustomer:g(k),isPaymentDataRequired:f(k),isPaymentDataSubmitted:S(k),getSignInEmail:v(k),getInstruments:w(k),getCustomerAccountFields:I(k),getBillingAddressFields:_(k),getShippingAddressFields:C(k),getPickupOptions:P(k),getUserExperienceSettings:O(k),getPaymentProviderCustomer:A(k)}))}(),t=function(){const e=sv(e=>e,e=>()=>{for(const t of Object.keys(e)){const i=e[t]();if(i)return i}}),t=av(({shippingStrategies:e})=>e.getSelectOptionError,({consignments:e})=>e.getUpdateShippingOptionError,(e,t)=>i=>e()||t(i));return Oe(i=>{const n={getLoadCheckoutError:i.checkout.getLoadError,getUpdateCheckoutError:i.checkout.getUpdateError,getSubmitOrderError:i.paymentStrategies.getExecuteError,getFinalizeOrderError:i.paymentStrategies.getFinalizeError,getLoadOrderError:i.order.getLoadError,getLoadCartError:i.cart.getLoadError,getLoadBillingCountriesError:i.countries.getLoadError,getLoadShippingCountriesError:i.shippingCountries.getLoadError,getLoadPaymentMethodsError:i.paymentMethods.getLoadError,getLoadPaymentMethodError:i.paymentMethods.getLoadMethodError,getInitializePaymentError:i.paymentStrategies.getInitializeError,getSignInError:i.customerStrategies.getSignInError,getSignOutError:i.customerStrategies.getSignOutError,getInitializeCustomerError:i.customerStrategies.getInitializeError,getLoadShippingOptionsError:i.consignments.getLoadShippingOptionsError,getSelectShippingOptionError:t(i),getContinueAsGuestError:i.billingAddress.getContinueAsGuestError,getUpdateBillingAddressError:i.billingAddress.getUpdateError,getUpdateSubscriptionsError:i.subscriptions.getUpdateError,getUpdateShippingAddressError:i.shippingStrategies.getUpdateAddressError,getDeleteConsignmentError:i.consignments.getDeleteError,getUpdateConsignmentError:i.consignments.getUpdateError,getCreateConsignmentsError:i.consignments.getCreateError,getInitializeShippingError:i.shippingStrategies.getInitializeError,getApplyStoreCreditError:i.storeCredit.getApplyError,getApplyCouponError:i.coupons.getApplyError,getRemoveCouponError:i.coupons.getRemoveError,getApplyGiftCertificateError:i.giftCertificates.getApplyError,getRemoveGiftCertificateError:i.giftCertificates.getRemoveError,getLoadInstrumentsError:i.instruments.getLoadError,getDeleteInstrumentError:i.instruments.getDeleteError,getLoadConfigError:i.config.getLoadError,getSignInEmailError:i.signInEmail.getSendError,getCreateCustomerAccountError:i.customer.getCreateAccountError,getCreateCustomerAddressError:i.customer.getCreateAddressError,getPickupOptionsError:i.pickupOptions.getLoadError,getLoadExtensionsError:i.extensions.getLoadError};return Object.assign({getError:e(n)},n)})}(),i=function(){const e=sv(e=>e,e=>()=>Object.keys(e).some(t=>e[t]())),t=av(({shippingStrategies:e})=>e.isSelectingOption,({consignments:e})=>e.isUpdatingShippingOption,(e,t)=>i=>e()||t(i)),i=av(({customerStrategies:e})=>e.isInitializing,({customerStrategies:e})=>e.isSigningIn,({customerStrategies:e})=>e.isSigningOut,({customerStrategies:e})=>e.isExecutingPaymentMethodCheckout,({customerStrategies:e})=>e.isWidgetInteracting,(e,t,i,n,r)=>o=>e(o)||t(o)||i(o)||n(o)||r(o)),n=av(({shippingStrategies:e})=>e.isInitializing,({shippingStrategies:e})=>e.isUpdatingAddress,({shippingStrategies:e})=>e.isSelectingOption,({shippingStrategies:e})=>e.isWidgetInteracting,(e,t,i,n)=>r=>e(r)||t(r)||i(r)||n(r)),r=av(({paymentStrategies:e})=>e.isInitializing,({paymentStrategies:e})=>e.isExecuting,({paymentStrategies:e})=>e.isFinalizing,({paymentStrategies:e})=>e.isWidgetInteracting,(e,t,i,n)=>r=>e(r)||t(r)||i(r)||n(r)),o=av(({paymentStrategies:e})=>e.isExecuting,({checkout:e})=>e.isExecutingSpamCheck,(e,t)=>i=>e(i)||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,isCustomerStepPending:i(a),isShippingStepPending:n(a),isPaymentStepPending:r(a),isLoadingPickupOptions:a.pickupOptions.isLoading};return Object.assign({isPending:e(s)},s)})}();return n=>({data:e(n),errors:t(n),statuses:i(n)})}());return new rv(c,E,O,function(e,t){const i={[Hi.ConsignmentsChanged]:Ki};return new Yi(e,t,i)}(E,O),new tt(new at(d),f),w,p,new Ht(new $t(d),w,g),new hg(new mg(d),h),new Im(new _m(d,{locale:n})),new Ot(new zt(d)),new Zt(function(e,t){const i=new Bt,n=a(),r=new Qt(t),o=new ti(r,new St(new bt(t)),new ni(new ri(t))),s=new ui(vi(n),new fi(t)),d=new Ht(new $t(t),o,s);return i.register("default",()=>new Si(e,d)),i}(c,d),C,I,s),new ut,new Nt(new xt(d)),new xg(new jg(l,d)),v,new zm(new Nm(d)),new jm(function(e,t,i){const n=new zy({defaultToken:Lm.CREDIT_CARD}),r=a(),s=new Dy,d=new uy(t),c=new Qt(i),l=new Vm(c),u=new km(new Em(i),l),h=new Jm(vi(o())),p=new ly(d,u,s,h),m=Ee(),y=((e,t)=>new Gy(new Vy(e,t)))(m,h),g=new cy(e);return n.register(Lm.CONVERGE,()=>new Ly(e,u,p,g,m)),n.register(Lm.PPSDK,()=>new Ky(e,u,((e,t,i,n,r)=>{const o=new Zy;return o.register(Wy.CARD,()=>new Qy(e,t,r,n)),o.register(Wy.NONE,()=>new eg(i,n)),o.register(Wy.UNSUPPORTED,()=>{}),o})(e,u,i,y,g),new rg(i,y),new Gm("PPSDK"))),n.register(Lm.WE_PAY,()=>new og(e,u,p,g,new ag(r))),n}(c,l,d),_,v,g,I,s),new Ug(new qg(d)),new vg(new fg(d,{locale:n}),c),new Vg(function(e,t){const i=new Bt,n=Ng(e),r=new Qt(t),o=new mg(t),s=new hg(o,r),d=new zm(new Nm(t)),c=a(),l=new Cg(new bg(t)),u=new tt(new at(t),l),h=window,p=new bn(n);return i.register("amazonpay",()=>new $g(e,s,new zm(new Nm(t)),yn(),new Vg(i))),i.register("stripeupe",()=>new Qg(e,new ka(c),s,d)),i.register("braintreeacceleratedcheckout",()=>new Yg(e,u,s,d,new dg,new vo(new qn(a(),h,p),h))),i.register("paypalcommerceacceleratedcheckout",()=>new Zg(e,u,s,d,new dg,Rs(),js())),i.register("default",()=>new Kg(e,s)),i}(c,d)),new ev(new tv(d)),g,new wg(new Ig(d)),f,S,b,P)}class QS extends Ji{constructor(e){super(e||"An unexpected error has occurred during config creation process. Please try again later."),this.name="AmazonPayV2ConfigCreationError",this.type="amazon_pay_v2_config_creation_error"}}function ew(e){return e instanceof Object&&"buyNowInitializeOptions"in e}var tw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class iw{constructor(e,t,i){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t,this.amazonPayV2ConfigRequestSender=i}initialize(e){var t;return tw(this,void 0,void 0,function*(){const{methodId:i,containerId:n,amazonpay:r}=e,{buttonColor:o}=r||{};if(!i||!n)throw new gn('Unable to proceed because "methodId" or "containerId" argument is not provided.');const{getPaymentMethodOrThrow:a}=this.paymentIntegrationService.getState(),s=a(i),{initializationData:d}=s;yield this.amazonPayV2PaymentProcessor.initialize(s),r||(yield this.paymentIntegrationService.loadDefaultCheckout());const c=ew(r)?void 0:r;ew(r)&&"function"==typeof(null===(t=r.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)&&(this._buyNowInitializeOptions=r.buyNowInitializeOptions,this.amazonPayV2PaymentProcessor.updateBuyNowFlowFlag(!0)),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:n,methodId:i,options:c,placement:an.Cart,buttonColor:o,isButtonMicroTextDisabled:null==d?void 0:d.isButtonMicroTextDisabled}),this._buyNowInitializeOptions&&this.amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(this._getCheckoutCreationRequestConfig.bind(this))})}deinitialize(){return this.amazonPayV2PaymentProcessor.deinitialize()}_createBuyNowCartOrThrow(){var e,t;return tw(this,void 0,void 0,function*(){const i=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!i)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(i)}catch(e){throw new Zn}})}_createCheckoutConfig(e){return tw(this,void 0,void 0,function*(){try{const t=(yield this.amazonPayV2ConfigRequestSender.createCheckoutConfig(e)).body,{payload:i,public_key:n}=t,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(t,["payload","public_key"]);return Object.assign({payloadJSON:i,publicKeyId:n},r)}catch(e){throw new QS}})}_getCheckoutCreationRequestConfig(){return tw(this,void 0,void 0,function*(){const e=yield this._createBuyNowCartOrThrow(),t={amount:String(e.baseAmount),currencyCode:e.currency.code};return{createCheckoutSessionConfig:yield this._createCheckoutConfig(e.id),estimatedOrderAmount:t,productType:0===en(e)?dn.PayOnly:dn.PayAndShip}})}}class nw{constructor(e){this._requestSender=e}createCheckoutConfig(e){const t={cartId:e},i=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return this._requestSender.post("/api/storefront/payment/amazonpay",{headers:i,body:t})}}const rw=Rt(e=>{const t=i(),n=new nw(t),r=yn();return new iw(e,r,n)},[{id:"amazonpay"}]);var ow,aw,sw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(ow||(ow={})),function(e){e.Black="black",e.White="white",e.WhiteBorder="white-border"}(aw||(aw={}));class dw{constructor(e,t,i,n,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=i,this._braintreeSdk=n,this._applePayScriptLoader=r,this._onAuthorizeCallback=V,this._subTotalLabel=ow.Subtotal,this._shippingLabel=ow.Shipping}initialize(e){var t,i;return sw(this,void 0,void 0,function*(){const{methodId:n,containerId:r,applepay:o}=e;if(!n||!o)throw new Qi(Zi.MissingPaymentMethod);yield this._applePayScriptLoader.loadSdk();const{onPaymentAuthorize:a,buyNowInitializeOptions:s,requiresShipping:d}=o;this._requiresShipping=d,this._buyNowInitializeOptions=s,this._onAuthorizeCallback=a,s||(yield this._paymentIntegrationService.loadDefaultCheckout()),yield this._paymentIntegrationService.loadPaymentMethod(n);const c=this._paymentIntegrationService.getState();return this._paymentMethod=c.getPaymentMethodOrThrow(n),c.getCart()&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection()),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===jn.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken),this._applePayButton=this._createButton(r,null===(i=this._paymentMethod.initializationData)||void 0===i?void 0:i.styleOption),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),Promise.resolve()})}deinitialize(){return Promise.resolve()}_createButton(e,t){const i=document.getElementById(e);if(!i)throw new gn("Unable to create wallet button without valid container ID.");const n=this._createApplePayButtonElement(t);return i.appendChild(n),n}_createApplePayButtonElement(e){const t=document.createElement("apple-pay-button");return t.setAttribute("buttonstyle",(e=>{switch(e){case aw.White:return"white";case aw.WhiteBorder:return"white-outline";case aw.Black:default:return"black"}})(e)),t.setAttribute("type","plain"),t.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),t}_handleWalletButtonClick(e){var t;return sw(this,void 0,void 0,function*(){if(e.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new Qi(Zi.MissingPaymentMethod);if(this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody){const{countryCode:e,currencyCode:i,merchantCapabilities:n,supportedNetworks:r,storeName:o}=this._paymentMethod.initializationData,a=this._getRequestWithEmptyTotal(e,i,r,n);this._requiresShipping&&(null===(t=a.requiredShippingContactFields)||void 0===t||t.push("postalAddress"));const s=this._sessionFactory.create(a);this._handleApplePayEvents(s,this._paymentMethod,o),s.begin()}else{const e=this._paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getStoreConfigOrThrow(),n=e.getCheckoutOrThrow(),r=this._getBaseRequest(t,n,i,this._paymentMethod),o=this._sessionFactory.create(r);this._handleApplePayEvents(o,this._paymentMethod,i.storeProfile.storeName),o.begin()}})}_getRequestWithEmptyTotal(e,t,i,n){return{countryCode:e,currencyCode:t,supportedNetworks:i,merchantCapabilities:n,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}}_getBaseRequest(e,t,i,n){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=i,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=n,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,i){e.onvalidatemerchant=i=>sw(this,void 0,void 0,function*(){try{const{body:n}=yield this._onValidateMerchant(t,i);e.completeMerchantValidation(n)}catch(e){throw new Error("Merchant validation failed")}}),this._buyNowInitializeOptions&&!this._requiresShipping&&(e.onpaymentmethodselected=()=>sw(this,void 0,void 0,function*(){yield this._createBuyNowCart(),this._handlePaymentMethodSelected(e)})),e.onshippingcontactselected=t=>sw(this,void 0,void 0,function*(){this._buyNowInitializeOptions&&this._requiresShipping&&(yield this._createBuyNowCart()),yield this._handleShippingContactSelected(e,i,t)}),e.onshippingmethodselected=t=>sw(this,void 0,void 0,function*(){yield this._handleShippingMethodSelected(e,i,t)}),e.oncancel=()=>sw(this,void 0,void 0,function*(){try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){throw new Vn}}),e.onpaymentauthorized=i=>sw(this,void 0,void 0,function*(){return this._onPaymentAuthorized(i,e,t)})}_createBuyNowCart(){var e,t;return sw(this,void 0,void 0,function*(){try{const i=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!i)throw new Qi(Zi.MissingCart);const n=yield this._paymentIntegrationService.createBuyNowCart(i);yield this._paymentIntegrationService.loadCheckout(n.id);const r=this._paymentIntegrationService.getState(),{shouldExecuteSpamCheck:o}=r.getCheckoutOrThrow();o&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection())}catch(e){throw new Zn}})}_handlePaymentMethodSelected(e){const t=this._paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new Qi(Zi.MissingPaymentMethod);const o=this._getBaseRequest(i,r,n,this._paymentMethod);delete o.total.type,e.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})}_handleShippingContactSelected(e,t,i){var n;return sw(this,void 0,void 0,function*(){const r=this._transformContactToAddress(i.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){throw e.abort(),new Error("Shipping address update failed")}let o=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:a}}=o.getCartOrThrow();let s=o.getCheckoutOrThrow();const d=null===(n=s.consignments[0].selectedShippingOption)||void 0===n?void 0:n.id,c=s.consignments[0].availableShippingOptions,l=null==c?void 0:c.find(({id:e})=>e===d),u=null==c?void 0:c.filter(e=>e.id!==d),h=l?[{label:l.description,amount:`${l.cost.toFixed(a)}`,detail:l.additionalDescription,identifier:l.id}]:[];if(u&&[...u.filter(e=>e.isRecommended),...u.filter(e=>!e.isRecommended)].forEach(e=>h.push({label:e.description,amount:`${e.cost.toFixed(a)}`,detail:e.additionalDescription,identifier:e.id})),!(c instanceof Array))throw new Error("Shipping options not available.");if(0===c.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:t,amount:`${s.grandTotal.toFixed(a)}`},[]);const p=c.find(e=>e.isRecommended),m=p?p.id:c[0].id,y=l?l.id:m;try{yield this._updateShippingOption(y)}catch(e){throw new Error("Shipping options update failed")}o=this._paymentIntegrationService.getState(),s=o.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:h,newTotal:{type:"final",label:t,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_handleShippingMethodSelected(e,t,i){return sw(this,void 0,void 0,function*(){const{shippingMethod:{identifier:n}}=i;try{yield this._updateShippingOption(n)}catch(t){throw e.abort(),new Error("Shipping option selection update failed.")}const r=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:o}}=r.getCartOrThrow(),a=r.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:t,amount:`${a.grandTotal.toFixed(o)}`},newLineItems:this._getUpdatedLineItems(a,o)})})}_getUpdatedLineItems(e,t){const i=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>i.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),i.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),i}_updateShippingOption(e){return sw(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return sw(this,void 0,void 0,function*(){const i=[`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:i})})}_onPaymentAuthorized(e,t,i){var n;return sw(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===(n=i.initializationData)||void 0===n?void 0:n.gateway)===jn.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:i.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){throw t.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete")}})}_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 sw(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const cw=Rt(e=>{const{getHost:t}=e.getState(),n=new bn(e);return new dw(i({host:t()}),e,new Yn,new Ln(new qn(a(),window,n)),new Kn(new r))},[{id:"applepay"}]);var lw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class uw{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){var t;return lw(this,void 0,void 0,function*(){const{bigcommerce_payments:i,containerId:n,methodId:r}=e,o=Boolean(null==i?void 0:i.buyNowInitializeOptions);if(!r)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(o&&!i.currencyCode)throw new gn('Unable to initialize payment because "options.bigcommerce_payments.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=i.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.bigcommerce_payments.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?i.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(n,r,i,o)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i,n){var r,o;const{buyNowInitializeOptions:a,style:s,onComplete:d,onEligibilityFailure:c}=i,l=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),u=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:h,isAppSwitchEnabled:p}=u.initializationData||{},m=Object.assign(Object.assign({},!n&&this.isPaypalCommerceAppSwitchEnabled(t)&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)}),y={onClick:()=>this.handleClick(a),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},g=Object.assign(Object.assign({},!p&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,d)}),v=Object.assign(Object.assign(Object.assign({fundingSource:l.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(s)},m),a&&y),h&&g),f=l.Buttons(v);f.isEligible()?(null===(r=f.hasReturned)||void 0===r?void 0:r.call(f))&&this.isPaypalCommerceAppSwitchEnabled(t)?null===(o=f.resume)||void 0===o||o.call(f):f.render(`#${e}`):c&&"function"==typeof c?c():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return lw(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return lw(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return lw(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){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return lw(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){if("string"==typeof e)throw new Error(e);throw e}})}isPaypalCommerceAppSwitchEnabled(e){var t,i;return null!==(i=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==i&&i}}const hw=Rt(e=>new uw(e,vr(e)),[{id:"bigcommerce_payments"}]);var pw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class mw{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.payPalSdkHelper=i}initialize(e){return pw(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:r,currencyCode:o,messagingContainerId:a}=t||{},s=!!r;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(s&&!o)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');s||(yield this.paymentIntegrationService.loadDefaultCheckout());const d=this.paymentIntegrationService.getState(),c=s?o:d.getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,c,!1),this.renderButton(i,n,t);const l=a&&document.getElementById(a);if(c&&l){const e=d.getPaymentMethodOrThrow(n),{paypalBNPLConfiguration:t=[]}=e.initializationData||{},i=t&&t.find(({id:e})=>"cart"===e);if(!(null==i?void 0:i.status))return;l.removeAttribute("data-pp-style-logo-type"),l.removeAttribute("data-pp-style-logo-position"),l.removeAttribute("data-pp-style-text-color"),l.removeAttribute("data-pp-style-text-size");const r=yield this.payPalSdkHelper.getPayPalMessages(e,c);this.renderMessages(r,a,i)}})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:r,onComplete:o,onEligibilityFailure:a}=i,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c}=d.initializationData||{},l={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},u={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},h={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,o)},p=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let m=!1;p.forEach(t=>{if(!m){const i=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r)},l),n&&u),c&&h),o=s.Buttons(i);o.isEligible()?(o.render(`#${e}`),m=!0):a&&"function"==typeof a&&a()}}),m||this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return pw(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return pw(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return pw(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){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return pw(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){if("string"==typeof e)throw new Error(e);throw e}})}renderMessages(e,t,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:$d(i)};e.Messages(n).render(`#${t}`)}}const yw=Rt(e=>new mw(e,vr(e),zr()),[{id:"bigcommerce_payments_paylater"}]);var gw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class vw{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return gw(this,void 0,void 0,function*(){const{bigcommerce_payments_apms:t,containerId:i,methodId:n}=e,{apm:r,buyNowInitializeOptions:o,currencyCode:a}=t||{},s=!!o;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_apms.apm" argument is not provided.');if(s&&!a)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_apms.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.bigcommerce_payments_apms.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');s||(yield this.paymentIntegrationService.loadDefaultCheckout());const d=s?a:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,d,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{apm:n,buyNowInitializeOptions:r,style:o,onEligibilityFailure:a}=i,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();if(!Object.values(s.FUNDING).includes(n))throw new gn('Unable to initialize PayPal button because "options.bigcommerce_payments_apms.apm" argument is not valid funding source.');const d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(r),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:n,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o)},d),r&&c),u=s.Buttons(l);u.isEligible()?u.render(`#${e}`):a&&"function"==typeof a?a():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return gw(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const fw=Rt(e=>new vw(e,vr(e)),[{id:"bigcommerce_payments_apms"}]);var Sw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ww{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return Sw(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(a&&!o)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,s,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:r,onEligibilityFailure:o}=i,a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),n&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.bigCommercePaymentsIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.bigCommercePaymentsIntegrationService.getValidButtonStyle(e);return t.color===nr.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return Sw(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const Iw=Rt(e=>new ww(e,vr(e)),[{id:"bigcommerce_payments_venmo"}]);class _w{constructor(e,t,i=window){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=i}initialize(e){return t=this,i=void 0,r=function*(){const{bolt:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:r,style:o}=t||{};if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(r))throw new vn("Only buy now flow is implemented for Bolt button");if(!(null==r?void 0:r.storefrontApiToken)||"string"!=typeof r.storefrontApiToken)throw new gn('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l}=s||{};yield this.boltScriptLoader.loadBoltClient(c,d.testMode,l,"BigCommerce",r.storefrontApiToken),this.renderButton(i,a,o)},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}deinitialize(){return Promise.resolve()}renderButton(e,t,i){var n;"function"==typeof(null===(n=this.boltHostWindow.BoltConnect)||void 0===n?void 0:n.setupProductPageCheckout)&&(this.addButtonContainer(e,t,i),this.boltHostWindow.BoltConnect.setupProductPageCheckout())}addButtonContainer(e,t,i){const n=document.getElementById(e);if(!n)return;const r=document.createElement("div"),o=document.createElement("object");r.setAttribute("id","product-page-checkout-wrapper"),r.setAttribute("class","bolt-button-wrapper"),r.setAttribute("style","display:none"),r.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(t,i)),o.setAttribute("class","bolt-product-checkout-button"),r.append(o),n.innerHTML="",n.append(r)}getBoltObjectData(e,t){const{initializationData:i,config:n}=e,{publishableKey:r,developerConfig:o}=i||{},a=this.boltScriptLoader.getDomainURL(!!n.testMode,o),s=this.getButtonHeight(null==t?void 0:t.size),d=this.getButtonBorderRadius(null==t?void 0:t.shape,s);return xe({url:`https://${a}/v1/checkout_button`,query:{publishable_key:r,variant:"ppc",height:s,border_radius:d}})}getButtonHeight(e){if(e)switch(e){case Xr.Small:return 25;case Xr.Large:return 45;case Xr.Medium:default:return 40}}getButtonBorderRadius(e,t){if(e)switch(e){case Qr.Pill:return t?Math.round(t/2):void 0;case Qr.Rect:default:return 4}}}const Cw=Rt(e=>new _w(e,new no(a())),[{id:"bolt"}]);function bw(e){const{color:t,fundingicons:i,height:n=40,layout:r,shape:o,size:a,tagline:s}=e||{},d={color:t,fundingicons:i,height:Pw(n),layout:r,shape:o||"rect",size:a,tagline:s};return H(d,k)}function Pw(e){const t=Number(e);return!t||Number.isNaN(t)?40:t>55?55:t<25?25:t}var Ow=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ew{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return Ow(this,void 0,void 0,function*(){const{braintreepaypal:t,containerId:i,methodId:n}=e;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new gn('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(n),{clientToken:s,config:d,initializationData:c}=a;if(!s||!c)throw new Qi(Zi.MissingPaymentMethod);const l={currency:r,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(l,e=>{this.renderPayPalButton(e,t,i,n,!!d.testMode)},e=>this.handleError(e,i,t.onError))})}deinitialize(){return Ow(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,i,n,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;if(c){const l=c.Buttons({env:r?"sandbox":"production",fundingSource:c.FUNDING.PAYPAL,style:bw(o),createOrder:()=>this.setupPayment(e,t,n),onApprove:t=>this.tokenizePayment(t,e,n,a,s)});l.isEligible()?l.render(`#${i}`):d&&"function"==typeof d&&d()}else this.braintreeIntegrationService.removeElement(i)}setupPayment(e,t,i){var n;return Ow(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(i),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?cl(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!1,intent:null===(n=c.initializationData)||void 0===n?void 0:n.intent})}catch(e){throw r&&(zn(e)||e instanceof Ji)&&r(e),e}})}tokenizePayment(e,t,i,n,r){return Ow(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:i,action:n?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(zn(e)||e instanceof Ji)&&r(e),e}})}createBuyNowCart(e){return Ow(this,void 0,void 0,function*(){if(!e)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new Zn}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!zn(e))throw e;i(e)}}const Aw=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t);return new Ew(e,Ee(),n,t)},[{id:"braintreepaypal"}]);var Tw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class kw{constructor(e,t,i,n,r){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeMessages=n,this.braintreeHostWindow=r}initialize(e){var t,i;return Tw(this,void 0,void 0,function*(){const{braintreepaypalcredit:n,containerId:r,methodId:o}=e;if(!o)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');let a,s=this.paymentIntegrationService.getState();if(n.buyNowInitializeOptions){if(!n.currencyCode)throw new gn('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');a=n.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),s=this.paymentIntegrationService.getState(),a=s.getCartOrThrow().currency.code;const d=s.getPaymentMethodOrThrow(o),{clientToken:c,config:l,initializationData:u}=d;if(!c||!u)throw new Qi(Zi.MissingPaymentMethod);const h={currency:a,intent:u.intent,isCreditEnabled:u.isCreditEnabled,commit:!1},p=Wt(null!==(i=null===(t=s.getStoreConfig())||void 0===t?void 0:t.checkoutSettings.features)&&void 0!==i?i:{},"PAYPAL-5663.hide_braintree_card_banner_implementation_in_checkout_sdk");this.braintreeIntegrationService.initialize(c),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{!p&&n.messagingContainerId&&this.renderPayPalMessages(o,n.messagingContainerId),this.renderPayPalButton(e,n,r,o,!!l.testMode)},e=>this.handleError(e,r,n.onError))})}deinitialize(){return Tw(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,yo.CART)}renderPayPalButton(e,t,i,n,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;let l=!1;c&&[c.FUNDING.PAYLATER,c.FUNDING.CREDIT].forEach(u=>{const h=u===c.FUNDING.CREDIT?Object.assign({label:po.CREDIT},bw(o)):bw(o);if(!l){const o=c.Buttons({env:r?"sandbox":"production",fundingSource:u,style:h,createOrder:()=>this.setupPayment(e,t,n),onApprove:t=>this.tokenizePayment(t,e,n,a,s)});o.isEligible()?(o.render(`#${i}`),l=!0):c.FUNDING.CREDIT&&d&&"function"==typeof d&&d()}}),c&&l||this.braintreeIntegrationService.removeElement(i)}setupPayment(e,t,i){var n;return Tw(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(i),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?cl(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!0,intent:null===(n=c.initializationData)||void 0===n?void 0:n.intent})}catch(e){throw r&&(zn(e)||e instanceof Ji)&&r(e),e}})}tokenizePayment(e,t,i,n,r){return Tw(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:i,action:n?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(zn(e)||e instanceof Ji)&&r(e),e}})}createBuyNowCart(e){return Tw(this,void 0,void 0,function*(){if(!e)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new Zn}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!zn(e))throw e;i(e)}}const Dw=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t),r=new ol(e);return new kw(e,Ee(),n,r,t)},[{id:"braintreepaypalcredit"}]);var Mw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class zw{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i}initialize(e){return Mw(this,void 0,void 0,function*(){const{containerId:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState(),{clientToken:r,initializationData:o,config:a}=n.getPaymentMethodOrThrow(i);if(!r||!o)throw new Qi(Zi.MissingPaymentMethod);this.braintreeSdk.initialize(r);const s=yield this.braintreeSdk.getBraintreeVisaCheckout(),{currency:{code:d},cartAmount:c}=n.getCartOrThrow(),l=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),u=s.createInitOptions({paymentRequest:{currencyCode:d,subtotal:String(c)},settings:{shipping:{collectShipping:!0}}});this.createSignInButton(t),yield l.init(u),l.on("payment.success",e=>Mw(this,void 0,void 0,function*(){yield this.paymentSuccess(s,e)}))})}deinitialize(){return Promise.resolve()}paymentSuccess(e,t){return Mw(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.toVisaCheckoutAddress(n),billingAddress:a=this.toVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}toVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e){const t=document.querySelector(`#${e}`);if(!t)throw new Error("Need a container to place the button");return this.insertVisaCheckoutButton(t)}insertVisaCheckoutButton(e){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="flex-end",t.innerHTML='\n <img\n alt="Visa Checkout"\n class="v-button"\n role="button"\n src="https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178"\n />\n <a class="v-learn v-learn-default" style="text-align: right; display: block; font-size: 10px; color: #003366;" href="#" data-locale="en_US">Tell Me More</a>',e.appendChild(t),t}}const Nw=Rt(e=>{const t=window,i=new bn(e),n=new Ln(new qn(a(),t,i));return new zw(e,Ee(),n)},[{id:"braintreevisacheckout"}]);function xw(e){const{billingAddress:t,email:i,firstName:n,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:i,first_name:n,last_name:r,phone_number:o,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}function Fw(e){const{email:t,phone:i,shippingAddress:n}=e,r=(null==n?void 0:n.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:i,address_line_1:null==n?void 0:n.line1,address_line_2:null==n?void 0:n.line2,city:null==n?void 0:n.city,state:null==n?void 0:n.state,country_code:null==n?void 0:n.countryCode,postal_code:null==n?void 0:n.postalCode}}var Rw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};const Lw=e=>{const{color:t,height:i}=e;return{backgroundColor:(n=t||"",n===ho.WHITE?"#FFFFFF":"#3D95CE"),backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:`url("/app/assets/img/payment-providers/venmo-logo-${t===ho.WHITE?ho.BLUE:ho.WHITE}.svg")`,backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:`${i||40}px`,minWidth:"150px",height:"100%",width:"100%",border:t===ho.WHITE?"1px solid black":"none"};var n};class Bw{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i,this.onError=V}initialize(e){return Rw(this,void 0,void 0,function*(){const{braintreevenmo:t,containerId:i,methodId:n}=e;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{clientToken:o,initializationData:a}=r,{paymentButtonStyles:s}=a,{cartButtonStyles:d}=s||{},c=(null==t?void 0:t.style)||d;if(!o||!a)throw new Qi(Zi.MissingPaymentMethod);if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadDefaultCheckout(),this.onError=(null==t?void 0:t.onError)||this.handleError,this.braintreeSdk.initialize(o);try{const e=yield this.braintreeSdk.getVenmoCheckoutOrThrow();this.renderVenmoButton(e,i,null==t?void 0:t.buyNowInitializeOptions,c)}catch(e){(dl(e)||function(e){return e instanceof Pn}(e))&&this.handleInitializationVenmoError(e,i)}})}deinitialize(){return Rw(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}handleError(e){throw new Error(e.message)}createBuyNowCart(e){return Rw(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=null==e?void 0:e.getBuyNowCartRequestBody();if(!t)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new Zn}}})}handleInitializationVenmoError(e,t){return this.removeVenmoContainer(t),this.onError(e)}removeVenmoContainer(e){const t=document.getElementById(e);t&&t.remove()}renderVenmoButton(e,t,i,n){const r=document.getElementById(t),{color:o}=n||{};if(!r)throw new gn("Unable to create wallet button without valid container ID.");r.setAttribute("aria-label","Venmo"),Object.assign(r.style,Lw(n||{})),r.addEventListener("click",()=>Rw(this,void 0,void 0,function*(){r.setAttribute("disabled","true");const t=yield this.createBuyNowCart(i);e.tokenize&&e.tokenize((e,i)=>Rw(this,void 0,void 0,function*(){r.removeAttribute("disabled"),e&&this.onError(e),yield this.handlePostForm(i,null==t?void 0:t.id)}))})),o===ho.BLUE&&(r.addEventListener("mouseenter",()=>{r.style.backgroundColor="#0a7fc2"}),r.addEventListener("mouseleave",()=>{r.style.backgroundColor=Lw(n||{}).backgroundColor}))}handlePostForm(e,t){return Rw(this,void 0,void 0,function*(){const{deviceData:i}=yield this.braintreeSdk.getDataCollectorOrThrow(),{nonce:n,details:r}=e;this.formPoster.postForm("/checkout.php",Object.assign({nonce:n,provider:"braintreevenmo",payment_type:"paypal",device_data:i,action:"set_external_checkout",billing_address:JSON.stringify(xw(r)),shipping_address:JSON.stringify(Fw(r))},t&&{cart_id:t}))})}}const jw=Rt(e=>{const t=window,i=a(),n=new bn(e),r=new qn(i,t,n),o=new Ln(r);return new Bw(e,Ee(),o)},[{id:"braintreevenmo"}]);var Uw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class qw{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,i;return Uw(this,void 0,void 0,function*(){if(!e.methodId||!Xo(e.methodId))throw new gn('Unable to proceed because "methodId" is not a valid key.');if(this._methodId=e.methodId,!e.containerId)throw new gn('Unable to proceed because "containerId" is not a valid key.');const n=e[this._getMethodOrThrow()];if(!n)throw new gn("Unable to proceed without valid options.");const{buyNowInitializeOptions:r,currencyCode:o,buttonColor:a,buttonType:s,onError:d}=n;let c,l=this._paymentIntegrationService.getState();try{c=l.getPaymentMethodOrThrow(this._getMethodOrThrow())}catch(e){l=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodOrThrow()),c=l.getPaymentMethodOrThrow(this._getMethodOrThrow())}if(this._countryCode=null===(t=c.initializationData)||void 0===t?void 0:t.storeCountry,r){if(!o)throw new gn('Unable to initialize payment because "options.currencyCode" argument is not provided.');this._currencyCode=o,this._buyNowInitializeOptions=r,yield this._googlePayPaymentProcessor.initialize(()=>c,this._getGooglePayClientOptions(),!!r,o)}else yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initialize(()=>c,this._getGooglePayClientOptions());this._paymentButton=null!==(i=this._paymentButton)&&void 0!==i?i:this._googlePayPaymentProcessor.addPaymentButton(e.containerId,{buttonColor:null!=a?a:"default",buttonType:null!=s?s:"plain",onClick:this._handleClick(d)})})}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_handleClick(e){return t=>Uw(this,void 0,void 0,function*(){t.preventDefault();try{this._buyNowInitializeOptions?yield this._createBuyNowCartOrThrow(this._buyNowInitializeOptions):yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let i=t;if(Zo(t)){if("CANCELED"===t.statusCode)throw new Vn;i=new Kr(JSON.stringify(t))}throw null==e||e(new Kr("An error occurred while requesting your Google Pay payment details.")),i}})}_interactWithPaymentSheet(){var e;return Uw(this,void 0,void 0,function*(){const t=yield this._googlePayPaymentProcessor.showPaymentSheet(),i=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(t),n=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(t),r="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;i&&(yield this._paymentIntegrationService.updateBillingAddress(i)),n&&!(null===(e=this._buyNowCart)||void 0===e?void 0:e.lineItems.digitalItems.length)&&(yield this._paymentIntegrationService.updateShippingAddress(n)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodOrThrow(),t,r)})}_getGooglePayClientOptions(){return{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:e,shippingAddress:t,shippingOptionData:i,offerData:n})=>Uw(this,void 0,void 0,function*(){const{availableTriggers:r,addressChangeTriggers:o,shippingOptionsChangeTriggers:a,offerChangeTriggers:s}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!r.includes(e))return;const d=o.includes(e)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(t):void 0;a.includes(e)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(i.id));const{newOfferInfo:c,error:l}=s.includes(e)?yield this._googlePayPaymentProcessor.handleCoupons(n):{},u=l;return this._buyNowInitializeOptions?this._getBuyNowTransactionInfo(d,c,u):this._getTransactionInfo(d,c,u)})}}}_createBuyNowCartOrThrow(e){return Uw(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=e.getBuyNowCartRequestBody();try{this._buyNowCart=yield this._paymentIntegrationService.createBuyNowCart(t),yield this._paymentIntegrationService.loadCheckout(this._buyNowCart.id)}catch(e){if("string"==typeof e)throw new Zn(e);throw e}}})}_getBuyNowTransactionInfo(e,t,i){if(!this._buyNowCart)return;const{cartAmount:n}=this._buyNowCart,r=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:this._getCurrencyCodeOrThrow(),totalPrice:r||String(n),totalPriceStatus:qo.FINAL})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),i&&{error:i})}_getTransactionInfo(e,t,i){return Uw(this,void 0,void 0,function*(){yield this._paymentIntegrationService.loadCheckout();const n=this._googlePayPaymentProcessor.getTotalPrice(),{code:r}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:r,totalPriceStatus:qo.FINAL,totalPrice:n})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),i&&{error:i})})}_getMethodOrThrow(){return tn(this._methodId,()=>new nn(Xi.PaymentNotInitialized))}_getCurrencyCodeOrThrow(){return tn(this._currencyCode,()=>new gn('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}}const Vw=Rt(e=>{const t=i(),n=window,r=new bn(e),o=new Ln(new qn(a(),n,r));return new qw(e,new ia(ra(),new Ua(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),Gw=Rt(e=>new qw(e,new ia(ra(),new Wa(e,new Ga(a())),i(),Ee())),[{id:"googlepaypaypalcommerce"}]),Hw=Rt(e=>new qw(e,new ia(ra(),new Ja(e,new Mr(a())),i(),Ee())),[{id:"googlepay_bigcommerce_payments"}]),$w=Rt(e=>{const t=i();return new qw(e,new ia(ra(),new Jo("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),Ww=Rt(e=>{const t=i();return new qw(e,new ia(ra(),new Jo("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]),Yw=Rt(e=>new qw(e,new ia(ra(),new sa(e),i(),Ee())),[{id:"googlepayauthorizenet"}]),Kw=Rt(e=>{const t=i();return new qw(e,new ia(ra(),new ha(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),Jw=Rt(e=>new qw(e,new ia(ra(),new ma(e),i(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),Zw=Rt(e=>new qw(e,new ia(ra(),new va(e),i(),Ee())),[{id:"googlepayorbital"}]),Xw=Rt(e=>new qw(e,new ia(ra(),new xa(e,new ka(a())),i(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),Qw=Rt(e=>new qw(e,new ia(ra(),new La(e),i(),Ee())),[{id:"googlepayworldpayaccess"}]),eI=Rt(e=>new qw(e,new ia(ra(),new es(e,Ee()),i(),Ee())),[{id:"googlepaytdonlinemart"}]);var tI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class iI{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){var t;return tI(this,void 0,void 0,function*(){const{paypalcommerce:i,containerId:n,methodId:r}=e,o=Boolean(null==i?void 0:i.buyNowInitializeOptions);if(!r)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(o&&!i.currencyCode)throw new gn('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=i.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?i.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalCommerceIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(n,r,i,o)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i,n){var r,o;const{buyNowInitializeOptions:a,style:s,onComplete:d,onEligibilityFailure:c}=i,l=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),u=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:h,isAppSwitchEnabled:p}=u.initializationData||{},m=Object.assign(Object.assign({},!n&&this.isPaypalCommerceAppSwitchEnabled(t)&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommerce"),onApprove:({orderID:e})=>this.paypalCommerceIntegrationService.tokenizePayment(t,e)}),y={onClick:()=>this.handleClick(a),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},g=Object.assign(Object.assign({},!p&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,d)}),v=Object.assign(Object.assign(Object.assign({fundingSource:l.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(s)},m),a&&y),h&&g),f=l.Buttons(v);f.isEligible()?(null===(r=f.hasReturned)||void 0===r?void 0:r.call(f))&&this.isPaypalCommerceAppSwitchEnabled(t)?null===(o=f.resume)||void 0===o||o.call(f):f.render(`#${e}`):c&&"function"==typeof c?c():this.paypalCommerceIntegrationService.removeElement(e)}handleClick(e){return tI(this,void 0,void 0,function*(){if(e){const t=yield this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return tI(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.paypalCommerceIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return tI(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){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return tI(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){if("string"==typeof e)throw new Error(e);throw e}})}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}}const nI=Rt(e=>new iI(e,ys(e)),[{id:"paypalcommerce"}]);var rI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class oI{constructor(e,t,i){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalCommerceSdk=i}initialize(e){var t;return rI(this,void 0,void 0,function*(){const{paypalcommercecredit:i,containerId:n,methodId:r}=e,{buyNowInitializeOptions:o,currencyCode:a,messagingContainerId:s}=i||{},d=!!o;if(!r)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(d&&!a)throw new gn('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(d&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');d||(yield this.paymentIntegrationService.loadDefaultCheckout());const c=this.paymentIntegrationService.getState(),l=d?a:c.getCartOrThrow().currency.code;yield this.paypalCommerceIntegrationService.loadPayPalSdk(r,l,!1),this.renderButton(n,r,i);const u=c.getStoreConfigOrThrow().checkoutSettings.features;if(null!==(t=u["PAYPAL-5557.Hide_ppc_banner_implementation"])&&void 0!==t&&t)return;const h=s&&document.getElementById(s);if(l&&h){const e=c.getPaymentMethodOrThrow(r),{paypalBNPLConfiguration:t=[]}=e.initializationData||{},i=t&&t.find(({id:e})=>"cart"===e);if(!(null==i?void 0:i.status))return;h.removeAttribute("data-pp-style-logo-type"),h.removeAttribute("data-pp-style-logo-position"),h.removeAttribute("data-pp-style-text-color"),h.removeAttribute("data-pp-style-text-size");const n=yield this.paypalCommerceSdk.getPayPalMessages(e,l);this.renderMessages(n,s,i)}})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:r,onComplete:o,onEligibilityFailure:a}=i,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c,isAppSwitchEnabled:l}=d.initializationData||{},u={createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:e})=>this.paypalCommerceIntegrationService.tokenizePayment(t,e)},h={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},p=Object.assign(Object.assign({},!l&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,o)}),m=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let y=!1;m.forEach(t=>{if(!y){const i=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.paypalCommerceIntegrationService.getValidButtonStyle(r)},u),n&&h),c&&p),o=s.Buttons(i);o.isEligible()?(o.render(`#${e}`),y=!0):a&&"function"==typeof a&&a()}}),y||this.paypalCommerceIntegrationService.removeElement(e)}handleClick(e){return rI(this,void 0,void 0,function*(){if(e){const t=yield this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return rI(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.paypalCommerceIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return rI(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){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return rI(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){if("string"==typeof e)throw new Error(e);throw e}})}renderMessages(e,t,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:Lh(i)};e.Messages(n).render(`#${t}`)}}const aI=Rt(e=>new oI(e,ys(e),qh()),[{id:"paypalcommercecredit"}]);var sI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class dI{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return sI(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(a&&!o)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalCommerceIntegrationService.loadPayPalSdk(n,s,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:r,onEligibilityFailure:o}=i,a=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:e})=>this.paypalCommerceIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),n&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.paypalCommerceIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.paypalCommerceIntegrationService.getValidButtonStyle(e);return t.color===os.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return sI(this,void 0,void 0,function*(){if(e){const t=yield this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const cI=Rt(e=>new dI(e,ys(e)),[{id:"paypalcommercevenmo"}]);var lI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class uI{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}initialize(e){return lI(this,void 0,void 0,function*(){const{paypalcommercealternativemethods:t,containerId:i,methodId:n}=e,{apm:r,buyNowInitializeOptions:o,currencyCode:a}=t||{},s=!!o;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.paypalcommercealternativemethods.apm" argument is not provided.');if(s&&!a)throw new gn('Unable to initialize payment because "options.paypalcommercealternativemethods.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');s||(yield this.paymentIntegrationService.loadDefaultCheckout());const d=s?a:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalIntegrationService.loadPayPalSdk(n,d,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{apm:n,buyNowInitializeOptions:r,style:o,onEligibilityFailure:a}=i,s=this.paypalIntegrationService.getPayPalSdkOrThrow();if(!Object.values(s.FUNDING).includes(n))throw new gn('Unable to initialize PayPal button because "options.paypalcommercealternativemethods.apm" argument is not valid funding source.');const d={createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercealternativemethod"),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(r),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:n,style:this.paypalIntegrationService.getValidButtonStyle(o)},d),r&&c),u=s.Buttons(l);u.isEligible()?u.render(`#${e}`):a&&"function"==typeof a?a():this.paypalIntegrationService.removeElement(e)}handleClick(e){return lI(this,void 0,void 0,function*(){if(e){const t=yield this.paypalIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const hI=Rt(e=>new uI(e,Qh(e)),[{id:"paypalcommercealternativemethods"}]);var pI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class mI{constructor(e,t,i){this.paymentIntegrationService=e,this.paypalExpressScriptLoader=t,this.formPoster=i}initialize(e){return pI(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!e.paypal)throw new gn;if(!t.config.merchantId)throw new Qi(Zi.MissingPaymentMethod);const i=yield this.paypalExpressScriptLoader.loadPaypalSDK(t.config.merchantId);this.renderButton(e,i)})}deinitialize(){return Promise.resolve()}renderButton(e,t){const{containerId:i,methodId:n,paypal:r}=e,{allowCredit:o,clientId:a,onPaymentError:s,shouldProcessPayment:d,style:c}=r,l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!l.config.merchantId)throw new Qi(Zi.MissingPaymentMethod);const u=l.config.merchantId,h=l.config.testMode?"sandbox":"production",p={[h]:a},m=t.FUNDING.CREDIT||"credit",y=o?[m]:[],g=o?[]:[m];return t.Button.render({env:h,client:p,commit:d,funding:{allowed:y,disallowed:g},style:this.getStyle(c),payment:(e,t)=>this.setupPayment(u,t,s),onAuthorize:(e,t)=>this.tokenizePayment(e,n,t,d)},i)}getStyle(e){const{color:t,fundingicons:i,label:n,layout:r,shape:o,size:a,tagline:s}=e||{};return{color:t,fundingicons:i,label:n,layout:r,shape:o||vp.RECT,size:"small"===a?mp.RESPONSIVE:a,tagline:s}}setupPayment(e,t,i){return pI(this,void 0,void 0,function*(){if(!t)throw new nn(Xi.CheckoutButtonNotInitialized);try{const i=yield this.paymentIntegrationService.loadDefaultCheckout(),{id:n}=i.getCartOrThrow(),r=i.getHost()||"";return(yield t.request.post(`${r}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:n},{headers:Object.assign({"X-API-INTERNAL":cr},hr)})).id}catch(e){throw i&&e instanceof Ji&&i(e),e}})}tokenizePayment(e,t,i,n){return pI(this,void 0,void 0,function*(){if(!i)throw new nn(Xi.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new Qi(Zi.MissingPayment);const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),o=yield i.payment.get(e.paymentID);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r.id,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(o.payer.payer_info)})})}}const yI=Rt(e=>new mI(e,new Ip(a()),Ee()),[{id:"paypalexpress"}]);var gI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class vI{constructor(e,t,i,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=i,this.loadingIndicator=n}initialize(e){return gI(this,void 0,void 0,function*(){const{stripeocs:t,containerId:i}=e||{};if(!t||!i)throw new nn(Xi.PaymentNotInitialized);const{methodId:n,gatewayId:r}=t;if(!n||!r)throw new Qi(Zi.MissingPaymentMethod);const o=yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:n}}),a=o.getPaymentMethodOrThrow(n,r),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!$s(a))throw new Qi(Zi.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);return this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this.paymentIntegrationService.loadDefaultCheckout(),yield this._mountExpressCheckoutElement(n,i,this._stripeClient,d),Promise.resolve()})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,i,n=40){return gI(this,void 0,void 0,function*(){const r=this._shouldRequireShippingAddress(),o=Object.assign(Object.assign(Object.assign({shippingAddressRequired:r},r?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),r?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ca.AUTO,applePay:Ca.NEVER,googlePay:Ca.NEVER,amazonPay:Ca.NEVER,paypal:Ca.NEVER,klarna:Ca.NEVER},buttonHeight:n}),{cartAmount:a=1}=this.paymentIntegrationService.getState().getCart()||{},s=Object.assign({mode:"payment",amount:this._toCents(a),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});this._stripeElements=i.elements(s),this._linkV2Element=this._stripeElements.create(Pa.EXPRESS_CHECKOUT,o),this._linkV2Element.mount(`#${t}`),this._initializeEvents(this._linkV2Element,e)})}_initializeEvents(e,t){this._shouldRequireShippingAddress()&&(e.on(Ea.SHIPPING_ADDRESS_CHANGE,e=>gI(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),e.on(Ea.SHIPPING_RATE_CHANGE,e=>gI(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),e.on(Ea.CONFIRM,e=>gI(this,void 0,void 0,function*(){return this._onConfirm(e,t)})),e.on(Ea.CANCEL,this._onCancel)}_onShippingAddressChange(e){return gI(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,i={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(i);const n=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==n?void 0:n.length)?e.resolve({shippingRates:n}):e.reject()})}_onCancel(){throw new Vn}_onShippingRateChange(e){return gI(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 gI(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 i=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(i)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,i,n,r,o,a,s,d;return gI(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(i=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===i?void 0:i.split(" ")[0])||(null===(r=null===(n=e.billingDetails)||void 0===n?void 0:n.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,i,n){var r,o,a,s,d,c,l;return{firstName:i,lastName:n,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,i,n){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:i,lastName:n,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 gI(this,void 0,void 0,function*(){if(!ca(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new nn(Xi.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:n}=i,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(i,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||n);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 i,n,r;return gI(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===(i=this._stripeClient)||void 0===i?void 0:i.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ca.IF_REQUIRED,confirmParams:{return_url:null===(n=s.confirmParams)||void 0===n?void 0:n.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Kr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return gI(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/checkout/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var i;const n=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:n},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:_a.Link})}}}_shouldRequireShippingAddress(){const{getCart:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e()||{};return!!(null==t?void 0:t.physicalItems.length)}_updateDisplayedPrice(){return gI(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){var e;if(!this._currencyCode){const t=null===(e=this.paymentIntegrationService.getState().getCart())||void 0===e?void 0:e.currency;t&&(this._currencyCode=t.code.toLowerCase())}return this._currencyCode}_getTotalPrice(){var e;return gI(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:t,getCart:i}=this.paymentIntegrationService.getState(),{decimalPlaces:n}=(null===(e=i())||void 0===e?void 0:e.currency)||{},r=J(t().outstandingBalance,n).toFixed(n);return this._toCents(+r)})}_getAvailableCountries(){var e;return gI(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=>nd.includes(e))})}_getAvailableShippingOptions(){var e,t;return gI(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const n=i[0],r=(n.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),o=null===(e=n.selectedShippingOption)||void 0===e?void 0:e.id;return o?r.sort(e=>e.id===o?-1:0):yield this._handleShippingOptionChange(null===(t=r[0])||void 0===t?void 0:t.id),r})}_getStripeShippingOption({id:e,cost:t,description:i}){return{id:e,displayName:i,amount:this._toCents(t)}}_handleShippingOptionChange(e){return gI(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 id(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),i=this._getAmountTransformer();return i?i.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}}const fI=Rt(e=>{const t=new ka(a()),i=new td({containerStyles:Qs});return new vI(e,t,new Zs(e,t),i)},[{id:"stripeocs"}]),SI=e=>{const t=ie(e);return document.getElementById(t)?SI(e):t};function wI(e){return Object.prototype.hasOwnProperty.call(e,"cacheKey")}class II{constructor(e){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=Object.assign({maxSize:0,isEqual:Be,onExpire:V},e)}getKey(...e){const t=this._resolveMap(...e),{index:i,parentMap:n}=t;let{map:r}=t;return r&&r.cacheKey?r.usedCount++:r=this._generateMap(n,e.slice(i)),this._removeLeastUsedMap(r),r.cacheKey}getUsedCount(...e){const{map:t}=this._resolveMap(...e);return t?t.usedCount:0}_resolveMap(...e){let t=0,i=this._map;for(;i.maps.length;){let n=!1;for(let r=0;r<i.maps.length;r++){const o=i.maps[r];if(this._options.isEqual(o.value,e[t])){if(i.maps.unshift(...i.maps.splice(r,1)),(0===e.length||t===e.length-1)&&wI(o))return{index:t,map:o,parentMap:i};n=!0,i=o,t++;break}}if(!n)break}return{index:t,parentMap:i}}_generateMap(e,t){let i,n=0,r=e;do{i={maps:[],parentMap:r,usedCount:1,value:t[n]},r.maps.unshift(i),r=i,n++}while(n<t.length);const o=i;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 i=this._usedMaps.pop();i&&(this._removeMap(i),this._options.onExpire(i.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 _I(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(i=>{const n=Object.getOwnPropertyDescriptor(e.prototype,i);n&&"constructor"!==i&&Object.defineProperty(t.prototype,i,function(e,t,i){if("function"!=typeof i.value)return i;let n=new II,r=i.value,o=Pe(r);return xi(e,t,{get(){const e=(...e)=>{const t=o.call(this,...e);if(1===n.getUsedCount(...e))return t;const i=r.call(this,...e);return mv(i,t,{keyFilter:e=>!function(e){return 0===`${e}`.indexOf("$$")||0===`${e}`.indexOf("_")}(e)})?t:(o.cache.set(n.getKey(...e),i),i)};return Object.defineProperty(this,t,Object.assign(Object.assign({},i),{value:e})),e},set(e){n=new II,r=e,o=Pe(r)}})}(e.prototype,i,n))}),t}let CI=class{constructor(e){this._checkoutButton=e.checkoutButton}getInitializeButtonError(e){return this._checkoutButton.getInitializeError(e)}getDeinitializeButtonError(e){return this._checkoutButton.getDeinitializeError(e)}};CI=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([_I],CI);const bI=CI;let PI=class{constructor(e){this._checkoutButton=e.checkoutButton}isInitializingButton(e){return this._checkoutButton.isInitializing(e)}isDeinitializingButton(e){return this._checkoutButton.isDeinitializing(e)}};PI=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([_I],PI);const OI=PI;function EI(e){return{errors:new bI(e),statuses:new OI(e)}}let AI=class{constructor(e,t){this._store=e,this._buttonStrategyActionCreator=t,this._state=EI(this._store.getState()),this._store.subscribe(e=>{this._state=EI(e)})}getState(){return this._state}subscribe(e,...t){return this._store.subscribe(()=>e(this.getState()),e=>e.checkoutButton.getState(),...t.map(e=>t=>e(EI(t))))}initializeButton(e){const t=(i=e.containerId,/^\w[\w\-\:\.]*$/.test(i)?[e.containerId]:function(e,t){const i=document.querySelectorAll(e);if(!i.length)throw new Lt(`Unable to find any element with the specified selector: ${e}`);return Array.prototype.slice.call(i).map(e=>(e.id||(e.id=SI(t)),e.id))}(e.containerId,`${e.methodId}-container`));var i;return Promise.all(t.map(t=>{const i=this._buttonStrategyActionCreator.initialize(Object.assign(Object.assign({},e),{containerId:t})),n=`checkoutButtonStrategy:${e.methodId}:${t}`;return this._store.dispatch(i,{queueId:n})})).then(()=>this.getState())}deinitializeButton(e){const t=this._buttonStrategyActionCreator.deinitialize(e),i=`checkoutButtonStrategy:${e.methodId}`;return this._store.dispatch(t,{queueId:i}).then(()=>this.getState())}};AI=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],AI);const TI=AI;class kI{constructor(e,t,i){this._registry=e,this._registryV2=t,this._paymentMethodActionCreator=i}initialize(e){return t=>{const i={methodId:e.methodId,containerId:e.containerId};if(t.getState().checkoutButton.isInitialized(e.methodId,e.containerId))return ce();const n=e.currencyCode?{params:{currencyCode:e.currencyCode}}:{},r=Object.assign(Object.assign({},n),{timeout:e.timeout,useCache:!0});return se(me(l(Tv.InitializeButtonRequested,void 0,i)),this._paymentMethodActionCreator.loadPaymentMethod(e.methodId,r)(t),de(()=>this._getStrategy(e.methodId).initialize(e).then(()=>l(Tv.InitializeButtonSucceeded,void 0,i)))).pipe(ge(e=>Je(Tv.InitializeButtonFailed,e,i)))}}deinitialize(e){return t=>{const i={methodId:e.methodId};return t.getState().checkoutButton.isInitialized(e.methodId)?se(me(l(Tv.DeinitializeButtonRequested,void 0,i)),de(()=>this._getStrategy(e.methodId).deinitialize().then(()=>l(Tv.DeinitializeButtonSucceeded,void 0,i)))).pipe(ge(e=>Je(Tv.DeinitializeButtonFailed,e,i))):ce()}}_getStrategy(e){let t;try{t=this._registryV2.get({id:e})}catch(i){t=this._registry.get(e)}return t}}class DI extends Ze{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 MI,zI,NI,xI,FI,RI,LI,BI;class jI{constructor(e){this._scriptLoader=e,this._window=window}loadPaypal(e=""){return t=this,i=void 0,r=function*(){const t="//www.paypalobjects.com/api/checkout.min.js",i={async:!0,attributes:{"data-merchant-id":e}};if(e?yield this._scriptLoader.loadScript(t,i):yield this._scriptLoader.loadScript(t),!this._window.paypal)throw new DI;return this._window.paypal},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(MI||(MI={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(zI||(zI={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(NI||(NI={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(xI||(xI={})),function(e){e.PILL="pill",e.RECT="rect"}(FI||(FI={}));class UI{constructor(e,t,i,n,r=""){this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=i,this._formPoster=n,this._host=r}initialize(e){const t=e.paypal,i=this._store.getState(),n=this._paymentMethod=i.paymentMethods.getPaymentMethod(e.methodId);if(!t)throw new Lt;if(!n)throw new Xe(We.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(n.config.merchantId).then(i=>{var r,o;if(!n||!n.config.merchantId)throw new Xe(We.MissingPaymentMethod);const a=n.config.merchantId,s=n.config.testMode?"sandbox":"production",d={[s]:t.clientId},c=i.FUNDING.CREDIT||"credit",l=t.allowCredit?[c]:[],u=t.allowCredit?[]:[c];return i.Button.render({env:s,client:d,commit:t.shouldProcessPayment,funding:{allowed:l,disallowed:u},style:Object.assign(Object.assign({shape:FI.RECT},W(t.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===n.id&&"small"===(null===(r=t.style)||void 0===r?void 0:r.size)?zI.RESPONSIVE:null===(o=t.style)||void 0===o?void 0:o.size}),payment:(e,i)=>this._setupPayment(a,i,t.onPaymentError),onAuthorize:(e,i)=>this._tokenizePayment(e,i,t.shouldProcessPayment,t.onAuthorizeError)},e.containerId)})}deinitialize(){return this._paymentMethod=void 0,Promise.resolve()}_setupPayment(e,t,i){if(!t)throw new pi(si.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then(i=>{const n=i.cart.getCart(),r=n?n.id:"";return t.request.post(`${this._host}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:r},{headers:Object.assign({"X-API-INTERNAL":Ct},rt)})}).then(e=>e.id).catch(e=>{throw i&&i(e),e})}_tokenizePayment(e,t,i,n){if(!this._paymentMethod)throw new pi(si.CheckoutButtonNotInitialized);if(!t)throw new pi(si.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new Xe(We.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:i?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})})}}function qI(e){const{host:t}=null!=e?e:{},n=ZS({config:{meta:{host:null==e?void 0:e.host,locale:null==e?void 0:e.locale},errors:{},statuses:{}}}),r=i({host:t}),o=Ee({host:t}),s=function(e,t){const i=new jt;for(const[,n]of Object.entries(t))if(Ft(n))for(const t of n.resolveIds)i.register(t,()=>n(e));return i}(Ng(n),Ke);return new TI(n,new kI(function(e,t,i,n){const r=new Bt,o=a(),s=new Qt(t),d=new ti(s,new St(new bt(t)),new ni(new ri(t)));return r.register(wy.PAYPALEXPRESS,()=>new UI(e,d,new jI(o),i,n)),r}(n,r,o,t),s,new zm(new Nm(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"}(RI||(RI={}));class VI extends It{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"}(LI||(LI={}));class GI extends Ze{constructor(e,t=LI.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"}(BI||(BI={}));const HI="isCookieAllowed",$I="lastAllowCookieAttempt";let WI=class{constructor(e,t,i,n,r,o,a,s){this._iframeCreator=e,this._messageListener=t,this._messagePoster=i,this._loadingIndicator=n,this._requestSender=r,this._storage=o,this._location=a,this._options=s,this._isAttached=!1,this._options.onComplete&&this._messageListener.addListener(RI.CheckoutComplete,this._options.onComplete),this._options.onError&&this._messageListener.addListener(RI.CheckoutError,this._options.onError),this._options.onLoad&&this._messageListener.addListener(RI.CheckoutLoaded,this._options.onLoad),this._options.onFrameLoad&&this._messageListener.addListener(RI.FrameLoaded,this._options.onFrameLoad),this._options.onSignOut&&this._messageListener.addListener(RI.SignedOut,this._options.onSignOut),this._messageListener.addListener(RI.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:RI.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:BI.StyleConfigured,payload:this._options.styles}))}_attemptLogin(){return/^\/login\/token/.test(wi(this._options.url).pathname)?this._requestSender.post(this._options.url).then(({body:{redirectUrl:e}})=>e).catch(e=>Promise.reject(new VI(e))):Promise.resolve(this._options.url)}_allowCookie(){if(this._storage.getItem(HI))return Promise.resolve();this._storage.setItem(HI,!0),this._storage.setItem($I,Date.now());const{origin:e}=wi(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($I));return(!t||Date.now()-t>6e5)&&e instanceof GI&&e.subtype===LI.MissingContent?(this._storage.removeItem($I),this._storage.removeItem(HI),this._allowCookie()):Promise.reject()}};WI=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],WI);const YI=WI;class KI{constructor(e){this._options=e}createFrame(e,t){const i=document.getElementById(t),{timeout:n=6e4}=this._options||{};if(!i)throw new GI("Unable to embed the iframe because the container element could not be found.",LI.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",i.appendChild(r),this._toResizableFrame(r,n).catch(e=>{throw i.removeChild(r),e})}_toResizableFrame(e,t){return new Promise((i,n)=>{const r=window.setTimeout(()=>{n(new GI("Unable to embed the iframe because the content could not be loaded."))},t),o=t=>{if((t.origin===wi(e.src).origin||t.origin===Gi(wi(e.src)).origin)&&(_i(t.data,RI.FrameError)&&(a(),n(new GI(t.data.payload.message,LI.MissingContent))),_i(t.data,RI.FrameLoaded))){e.style.display="";const n=Ti({scrolling:!1,sizeWidth:!1,heightCalculationMethod:t.data.payload&&t.data.payload.contentId?"taggedElement":"lowestElement"},e);a(),i(n[n.length-1])}},a=()=>{window.removeEventListener("message",o),window.clearTimeout(r)};window.addEventListener("message",o)})}}function JI(e){const t=wi(e.url).origin;return new YI(new KI,new $i(t),new Ci(t),new td({styles:e.styles&&e.styles.loadingIndicator}),i(),new Gm("BigCommerce.EmbeddedCheckout"),window.location,e).attach()}function ZI(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 XI(e){return"object"==typeof e&&null!==e&&"message"in e&&"type"in e}let QI=class{constructor(e,t,i,n={}){this._messageListener=e,this._messagePoster=t,this._untargetedMessagePoster=i,this._messageHandlers=n,this._messageListener.listen()}postComplete(){const e={type:RI.CheckoutComplete};this._postMessage(e)}postError(e){const t={type:RI.CheckoutError,payload:this._transformError(e)};this._postMessage(t)}postFrameError(e){const t={type:RI.FrameError,payload:this._transformError(e)};this._postMessage(t,{untargeted:!0})}postFrameLoaded(e){const t={type:RI.FrameLoaded,payload:e};this._postMessage(t)}postLoaded(){const e={type:RI.CheckoutLoaded};this._postMessage(e)}postSignedOut(){const e={type:RI.SignedOut};this._postMessage(e)}receiveStyles(e){this._messageListener.addListener(BI.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 i=this._messageHandlers[t];i&&i.call(null,e)})}_transformError(e){return{message:e.message,type:XI(e)?e.type:void 0,subtype:XI(e)?e.subtype:void 0}}};QI=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],QI);const e_=QI;let t_=class{postComplete(){}postError(){}postFrameError(){}postFrameLoaded(){}postLoaded(){}postSignedOut(){}receiveStyles(){}};t_=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],t_);const i_=t_;function n_(e){Ge(939);const t=e.parentWindow||window.parent;return window===t?new i_:new e_(new $i(e.parentOrigin),new Ci(e.parentOrigin,t),new Ci("*",t),{[RI.FrameLoaded]:ZI})}const r_="en",o_="optimized_checkout";let a_=class{constructor(e,t){var i;this._logger=t;const{locale:n,locales:r,translations:o}=this._transformConfig(e);this._locale=n,this._locales=r,this._translations=o,this._formatters={},this._isCspNonceExperimentEnabled=null===(i=e.isCspNonceExperimentEnabled)||void 0===i||i}mapKeys(e){Object.keys(e).forEach(t=>{const i=`${o_}.${e[t]}`;this._translations[`${o_}.${t}`]=this._translations[i]})}getLocale(){return this._hasTranslations()?this._locale:r_}translate(e,t={}){var i;const n=`${o_}.${e}`;if("string"!=typeof this._translations[n])return this._logger.warn(`Translation key "${n}" is missing`),n;if(this._isCspNonceExperimentEnabled){this._formatters[n]||(this._formatters[n]=new je(this._escapeSpecialCharacters(this._translations[n]||""),this._locales[n],void 0,{ignoreTag:!0}));try{return this._formatters[n].format(this._transformData(t))}catch(e){if(this._isFormatError(e))return null!==(i=e.originalMessage)&&void 0!==i?i:"";throw e}}if(!this._formatters[n]){const e=new Ue(this._locales[n]);this._formatters[n]=e.compile(this._translations[n]||"")}return this._formatters[n](this._transformData(t))}_transformConfig(e={}){const t={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:e.locale||r_},i=e.locales||{},n=this._flattenObject(e.translations||{}),r=this._flattenObject(e.defaultTranslations||{}),o=this._flattenObject(e.fallbackTranslations||{});return ee(Object.keys(o),Object.keys(r),Object.keys(n)).forEach(a=>{var s,d;n&&n[a]?(t.translations[a]=n[a],t.locales[a]=i[a]||t.locale):r[a]?(t.translations[a]=r[a],t.locales[a]=null!==(s=e.defaultLocale)&&void 0!==s?s:r_):(t.translations[a]=o[a],t.locales[a]=null!==(d=e.fallbackLocale)&&void 0!==d?d:r_)}),t}_flattenObject(e,t={},i=""){try{Object.keys(e).forEach(n=>{const r=e[n],o=i?`${i}.${n}`:n;if(D(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,i)=>{const n=e[i];return t[i]=null==n?"":n,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''")}};a_=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],a_);const s_=a_;function d_(e={}){return new s_(e,gt())}let c_=class{constructor(e){this._storeConfig=e,this._customerFormatter=new No(this._storeConfig.shopperCurrency),this._storeFormatter=new No(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};c_=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],c_);const l_=c_;function u_(e){return new l_(e)}function h_(e){return e&&"ga"in e&&"function"==typeof e.ga}function p_(e,t){h_(window)&&window.ga("send",e,Object.assign(Object.assign({},t),{nonInteraction:!1}))}function m_(e){return y_(e).length>=8096}function y_(e){return Object.keys(e).reduce((t,i)=>{const n=typeof e[i];return"string"===n||"number"===n?[...t,`${i}=${e[i]}`]:"object"===n&&null!==e[i]?[...t,y_(e[i])]:t},[]).join("&")}var g_;!function(e){e[e.CUSTOMER=1]="CUSTOMER",e[e.SHIPPING=2]="SHIPPING",e[e.BILLING=3]="BILLING",e[e.PAYMENT=4]="PAYMENT"}(g_||(g_={}));const v_={customer:g_.CUSTOMER,shipping:g_.SHIPPING,billing:g_.BILLING,payment:g_.PAYMENT};class f_{constructor(e,t,i,{checkoutSteps:n}={}){if(this.checkoutService=e,this.analyticsExtraItemsManager=t,this.analytics=i,this._checkoutStarted=!1,this._completedSteps={},this._viewedSteps={},this._analyticStepOrder=["customer","shipping","billing","payment"],void 0!==n){if(n.some(e=>!(e in v_)))throw new Lt(`Invalid checkout steps provided. Valid values are: ${R(v_).join(", ")}.`);this._analyticStepOrder=n}}trackCheckoutStarted(){if(this._checkoutStarted)return;const e=this.getCheckout();if(!e)return;const{coupons:t,grandTotal:i,shippingCostTotal:n,taxTotal:r,cart:{lineItems:o,discountAmount:a,id:s}}=e,d=this.analyticsExtraItemsManager.saveExtraItemsData(s,o);this.analytics.track("Checkout Started",this.getTrackingPayload({revenue:i,shipping:n,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:i,orderId:n,orderAmount:r,shippingCostTotal:o,taxTotal:a,discountAmount:s,coupons:d,lineItems:c,cartId:l}=t;if(!i)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:n,revenue:r,shipping:o,tax:a,discount:s,coupons:d,extraItemsData:u,lineItems:c});if(h&&Kc(window)&&h_(window)&&m_(p))return p_("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=>{p_("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 i=this.getIdFromStep(t);if(!i)break;if(this.hasStepViewed(i)||this.trackViewed(i),i===e)break;this.hasStepCompleted(i)||this.trackCompleted(i)}}trackCompleted(e){const t=this.getSelectedShippingOption(),{code:i=""}=this.getShopperCurrency()||{},n=this.getPaymentMethodName(),r={step:e,currency:i};t&&(r.shipping_method=t.description),n&&(r.payment_method=n),r.shipping_method||r.payment_method||(r.shipping_method=" "),this.analytics.track("Checkout Step Completed",r);const o=t?t.id:"",a=e===g_.SHIPPING?`${e}-${o}`:e;this._completedSteps[a]=!0}getTrackingPayload({orderId:e,revenue:t,shipping:i,tax:n,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(i),tax:this.toShopperCurrency(n),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(),i=t?t.id:"";return Object.prototype.hasOwnProperty.call(this._completedSteps,e)||e===g_.SHIPPING&&Object.prototype.hasOwnProperty.call(this._completedSteps,`${e}-${i}`)}hasStepViewed(e){return!!this._viewedSteps[e]}getIdFromStep(e){const t=e.split(".");return v_[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 i=(t.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,price:e.listPrice,quantity:e.quantity,name:e.name})),n=t.giftCertificates.map(e=>({product_id:e.id,price:this.toShopperCurrency(e.amount),name:e.name,quantity:1}));return[...i,...[...t.physicalItems,...t.digitalItems].map(t=>{let i;t.options&&t.options.length&&(i=t.options.map(e=>`${e.name}:${e.value}`),i.sort());const n=Array.isArray(i)&&i.length?i.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:n},r&&{brand:r})}),...n]}}class S_{trackCheckoutStarted(){}trackOrderComplete(){}trackStepViewed(){}trackStepCompleted(){}}function w_(e,t){const{data:i}=e.getState(),n=i.getConfig();if(!n)throw new Xe(We.MissingCheckoutConfig);const{isAnalyticsEnabled:r}=n.checkoutSettings;return r&&Kc(window)?new f_(e,new Yc(Te),window.analytics,t):new S_}function I_(e){return Boolean(e.hasOwnProperty("braintreeFastlane"))}class __{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"),i=null==t?void 0:t.initializationData.isBraintreeAnalyticsV2Enabled,n=I_(window)&&window.braintreeFastlane.events;return i&&n}_getBraintreeEventsOrThrow(){if(I_(window))return window.braintreeFastlane.events;throw new pn}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getBraintreeEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:i}=this._getBraintreeEventsOrThrow();i(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getBraintreeEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const i=this.checkoutService.getState(),n=i.data.getCart(),r=null===(e=i.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=i.data.getCustomer())||void 0===t?void 0:t.isGuest,a=i.data.getPaymentMethod("braintreeacceleratedcheckout"),s=[{treatment_group:!i.errors.getLoadPaymentMethodError("braintreeacceleratedcheckout")&&(null==a?void 0:a.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==n?void 0:n.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 i=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:i.length>1?"1":"0",apm_list:i.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 C_(e){return new __(e)}class b_{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,i=window,n=!!i.paypalFastlane&&!!i.paypalFastlane.events;return t&&n}_getPayPalEventsOrThrow(){const e=window;if(e.paypalFastlane&&e.paypalFastlane.events)return e.paypalFastlane.events;throw new pn}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getPayPalEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:i}=this._getPayPalEventsOrThrow();i(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getPayPalEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const i=this._checkoutService.getState(),n=i.data.getCart(),r=null===(e=i.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=i.data.getCustomer())||void 0===t?void 0:t.isGuest,a="paypalcommerceacceleratedcheckout",s=i.data.getPaymentMethod(a),d=[{treatment_group:!i.errors.getLoadPaymentMethodError(a)&&(null==s?void 0:s.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==n?void 0:n.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 i=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:i.length>1?"1":"0",apm_list:i.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 P_(e){return new b_(e)}var O_;class E_{constructor(e,t){this._host=e,this._hostedFormFactory=t}submitStoredCard(e,t){return i=this,n=void 0,o=function*(){const i=this._hostedForm;if(!i)throw new pi(si.PaymentNotInitialized);yield i.validate().then(()=>i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}function A_(e){const t=ZS();return new E_(e,new cy(t))}!function(e){e.CUSTOMER="customer",e.SHIPPING="shipping",e.BILLING="billing",e.PAYMENT="payment"}(O_||(O_={}));const T_=[O_.CUSTOMER,O_.SHIPPING,O_.BILLING,O_.PAYMENT];class k_{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 Xe(We.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:i,isComplete:n,orderId:r,orderAmount:o,shippingCostTotal:a,lineItems:s,cartId:d,coupons:c,channelId:l,taxTotal:u}=t;n&&this.bodlEvents.emitOrderPurchasedEvent({event_id:d,currency:i.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,i.code)})}stepCompleted(e){e&&T_.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={[O_.SHIPPING]:this._trackShippingStepCompleted.bind(this)}[e];t?t():this.bodlEvents.emit("bodl_checkout_step_completed",{step:e})}_trackShippingStepCompleted(){var e,t;const i=null===(t=null===(e=this.state)||void 0===e?void 0:e.getSelectedShippingOption())||void 0===t?void 0:t.description,n=this._getCommonCheckoutData();n&&i&&this.bodlEvents.emitShippingDetailsProvidedEvent(Object.assign(Object.assign({},n),{shipping_method:i}))}_getCommonCheckoutData(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getCheckout();if(!t)return null;const{cart:{cartAmount:i,currency:n,lineItems:r,id:o,coupons:a},channelId:s}=t;return{event_id:o,currency:n.code,cart_value:i,coupon_codes:a.map(e=>e.code.toUpperCase()),line_items:this._getProducts(r,n.code),channel_id:s}}_getProducts(e,t){const i=(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})),n=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[...i,...[...e.physicalItems,...e.digitalItems].map(e=>{let i;return e.options&&e.options.length&&(i=e.options.map(e=>`${e.name}:${e.value}`),i.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:(n=e,Array.isArray(n.categoryNames)?n.categoryNames:Array.isArray(n.categories)?_(n.categories).map(({name:e})=>e):[]),retail_price:e.retailPrice};var n}),...n].map(e=>Object.assign(Object.assign({},e),{product_id:String(e.product_id)}))}_hasStepCompleted(e){return this._completedSteps[e]}}class D_{checkoutBegin(){}orderPurchased(){}stepCompleted(){}customerEmailEntry(){}customerSuggestionInit(){}customerSuggestionExecute(){}customerPaymentMethodExecuted(){}showShippingMethods(){}selectedPaymentMethod(){}clickPayButton(){}paymentRejected(){}paymentComplete(){}exitCheckout(){}}function M_(e){return function(e){return"bodlEvents"in e}(window)?new k_(e,window.bodlEvents.checkout):new D_}export{Ri as ExtensionCommandType,Li as ExtensionQueryType,M_ as createBodlService,C_ as createBraintreeAnalyticTracker,qI as createCheckoutButtonInitializer,XS as createCheckoutService,u_ as createCurrencyService,n_ as createEmbeddedCheckoutMessenger,d_ as createLanguageService,P_ as createPayPalCommerceAnalyticTracker,w_ as createStepTracker,A_ as createStoredCardHostedFormService,n as createTimeout,JI as embedCheckout};
|
|
1
|
+
import*as e from"iframe-resizer";import*as t from"iframe-resizer/js/iframeResizer.contentWindow";import{createRequestSender as i,createTimeout as n}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{cond as m,constant as y,difference as g,each as v,filter as f,find as S,findIndex as w,flatMap as I,flatten as _,get as C,identity as b,includes as P,isArray as O,isEmpty as E,isEqual as A,isMatch as T,isNil as k,isObject as D,isPlainObject as M,isString as z,isUndefined as N,kebabCase as x,keyBy as F,keys as R,last as L,map as B,max as j,memoize as U,merge as q,noop as V,omit as G,omitBy as H,overSome as $,pick as W,pickBy as Y,reduce as K,round as J,some as Z,stubTrue as X,transform as Q,union as ee,uniq as te,uniqueId as ie,values as ne,without as re}from"lodash";import{Observable as oe,Subject as ae,concat as se,defer as de,empty as ce,from as le,fromEvent as ue,merge as he,noop as pe,of as me,throwError as ye}from"rxjs";import{catchError as ge,delay as ve,distinctUntilChanged as fe,filter as Se,map as we,retryWhen as Ie,shareReplay as _e,switchMap as Ce,take as be}from"rxjs/operators";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 Ne,stringifyUrl as xe}from"query-string";import{createSelector as Fe,createSelectorCreator as Re,defaultMemoize as Le}from"reselect";import{default as Be}from"shallowequal";import{IntlMessageFormat as je}from"intl-messageformat";import{default as Ue}from"messageformat";var qe={785:t=>{t.exports=e},939:e=>{e.exports=t}},Ve={};function Ge(e){var t=Ve[e];if(void 0!==t)return t.exports;var i=Ve[e]={exports:{}};return qe[e](i,i.exports,Ge),i.exports}Ge.d=(e,t)=>{for(var i in t)Ge.o(t,i)&&!Ge.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},Ge.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ge.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var He={};Ge.r(He),Ge.d(He,{createAmazonPayV2CustomerStrategy:()=>wn,createApplePayCustomerStrategy:()=>Jn,createBigCommercePaymentsCustomerStrategy:()=>Ir,createBigCommercePaymentsFastlaneCustomerStrategy:()=>qr,createBigCommercePaymentsPayLaterCustomerStrategy:()=>Hr,createBigCommercePaymentsVenmoCustomerStrategy:()=>Yr,createBoltCustomerStrategy:()=>ro,createBraintreeFastlaneCustomerStrategy:()=>ko,createBraintreePaypalCreditCustomerStrategy:()=>Co,createBraintreePaypalCustomerStrategy:()=>wo,createBraintreeVisaCheckoutCustomerStrategy:()=>zo,createGooglePayAdyenV2CustomerStrategy:()=>oa,createGooglePayAdyenV3CustomerStrategy:()=>aa,createGooglePayAuthorizeDotNetCustomerStrategy:()=>da,createGooglePayBigCommercePaymentsCustomerStrategy:()=>Za,createGooglePayBnzCustomerStrategy:()=>ga,createGooglePayBraintreeCustomerStrategy:()=>qa,createGooglePayCheckoutComCustomerStrategy:()=>pa,createGooglePayCybersourceCustomerStrategy:()=>ya,createGooglePayOrbitalCustomerStrategy:()=>fa,createGooglePayPayPalCommerceCustomerStrategy:()=>Ya,createGooglePayStripeCustomerStrategy:()=>Fa,createGooglePayStripeUpeCustomerStrategy:()=>Ra,createGooglePayTdOnlineMartCustomerStrategy:()=>ts,createGooglePayWorldpayAccessCustomerStrategy:()=>Ba,createPayPalCommerceCreditCustomerStrategy:()=>Is,createPayPalCommerceCustomerStrategy:()=>fs,createPayPalCommerceFastlaneCustomerStrategy:()=>Hs,createPayPalCommerceVenmoCustomerStrategy:()=>bs,createStripeLinkV2CustomerStrategy:()=>ad,createStripeUPECustomerStrategy:()=>Ks});var $e={};Ge.r($e),Ge.d($e,{createAdyenV2PaymentStrategy:()=>wd,createAdyenV3PaymentStrategy:()=>Pd,createAffirmPaymentStrategy:()=>kd,createAfterpayPaymentStrategy:()=>Rd,createAmazonPayV2PaymentStrategy:()=>jd,createApplePayPaymentStrategy:()=>Gd,createBigCommercePaymentsAlternativeMethodsPaymentStrategy:()=>vc,createBigCommercePaymentsCreditCardsPaymentStrategy:()=>mc,createBigCommercePaymentsFastlanePaymentStrategy:()=>ec,createBigCommercePaymentsPayLaterPaymentStrategy:()=>nc,createBigCommercePaymentsPaymentStrategy:()=>Jd,createBigCommercePaymentsRatePayPayPaymentStrategy:()=>sc,createBigCommercePaymentsRedirectAlternativeMethodsPaymentStrategy:()=>Sc,createBigCommercePaymentsVenmoPaymentStrategy:()=>_c,createBlueSnapDirectAPMPaymentStrategy:()=>qc,createBlueSnapDirectCreditCardPaymentStrategy:()=>jc,createBlueSnapV2PaymentStrategy:()=>Wc,createBoltPaymentStrategy:()=>el,createBraintreeAchPaymentStrategy:()=>rl,createBraintreeCreditCardPaymentStrategy:()=>Nl,createBraintreeFastlanePaymentStrategy:()=>wl,createBraintreeLocalMethodsPaymentStrategy:()=>gl,createBraintreePaypalPaymentStrategy:()=>hl,createBraintreeVenmoPaymentStrategy:()=>Ol,createBraintreeVisaCheckoutPaymentStrategy:()=>Cl,createCBAMPGSPaymentStrategy:()=>Ul,createCheckoutComAPMPaymentStrategy:()=>nu,createCheckoutComCreditCardPaymentStrategy:()=>Jl,createCheckoutComFawryPaymentStrategy:()=>Hl,createCheckoutComIdealPaymentStrategy:()=>eu,createCheckoutComSepaPaymentStrategy:()=>Xl,createClearpayPaymentStrategy:()=>su,createCreditCardPaymentStrategy:()=>du,createCyberSourcePaymentStrategy:()=>Cu,createCyberSourceV2PaymentStrategy:()=>Au,createExternalPaymentStrategy:()=>ku,createGooglePayAdyenV2PaymentStrategy:()=>Fu,createGooglePayAdyenV3PaymentStrategy:()=>Bu,createGooglePayAuthorizeNetPaymentStrategy:()=>ju,createGooglePayBigCommercePaymentsPaymentStrategy:()=>ih,createGooglePayBraintreePaymentStrategy:()=>$u,createGooglePayCheckoutComPaymentStrategy:()=>Uu,createGooglePayCybersourcePaymentStrategy:()=>qu,createGooglePayOrbitalPaymentStrategy:()=>Vu,createGooglePayPPCPPaymentStrategy:()=>Zu,createGooglePayStripePaymentStrategy:()=>Gu,createGooglePayTdOnlineMartPaymentStrategy:()=>nh,createGooglePayWorldpayAccessPaymentStrategy:()=>Hu,createHummPaymentStrategy:()=>ah,createKlarnaPaymentStrategy:()=>hh,createKlarnaV2PaymentStrategy:()=>vh,createLegacyPaymentStrategy:()=>Sh,createMolliePaymentStrategy:()=>Ph,createMonerisPaymentStrategy:()=>Th,createNoPaymentStrategy:()=>Dh,createOfflinePaymentStrategy:()=>zh,createOffsitePaymentStrategy:()=>Fh,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>ip,createPayPalCommerceCreditCardsPaymentStrategy:()=>op,createPayPalCommerceCreditPaymentStrategy:()=>Hh,createPayPalCommerceFastlanePaymentStrategy:()=>hp,createPayPalCommercePaymentStrategy:()=>Uh,createPayPalCommerceRatePayPaymentStrategy:()=>dp,createPayPalCommerceVenmoPaymentStrategy:()=>Yh,createPayPalProPaymentStrategy:()=>Pp,createPaypalExpressPaymentStrategy:()=>_p,createSagePayPaymentStrategy:()=>Ep,createSezzlePaymentStrategy:()=>Tp,createSquareV2PaymentStrategy:()=>Rp,createStripeCSPaymentStrategy:()=>om,createStripeOCSPaymentStrategy:()=>im,createStripeUPEPaymentStrategy:()=>Qp,createStripeV3PaymentStrategy:()=>Yp,createTDOnlineMartPaymentStrategy:()=>lm,createWorldpayAccessPaymentStrategy:()=>ym,createZipPaymentStrategy:()=>fm});var We,Ye,Ke={};function Je(e,t,i){return(n=t)&&n.type&&n.error?se(me(t),ye(h(e,t.payload,i))):ye(h(e,t,i));var n}Ge.r(Ke),Ge.d(Ke,{createAmazonPayV2ButtonStrategy:()=>rw,createApplePayButtonStrategy:()=>cw,createBigCommercePaymentsAlternativeMethodsButtonStrategy:()=>fw,createBigCommercePaymentsButtonStrategy:()=>hw,createBigCommercePaymentsPayLaterButtonStrategy:()=>yw,createBigCommercePaymentsVenmoButtonStrategy:()=>Iw,createBoltButtonStrategy:()=>Cw,createBraintreePaypalButtonStrategy:()=>Aw,createBraintreePaypalCreditButtonStrategy:()=>Dw,createBraintreeVenmoButtonStrategy:()=>jw,createBraintreeVisaCheckoutButtonStrategy:()=>Nw,createGooglePayAdyenV2ButtonStrategy:()=>$w,createGooglePayAdyenV3ButtonStrategy:()=>Ww,createGooglePayAuthorizeDotNetButtonStrategy:()=>Yw,createGooglePayBigCommercePaymentsButtonStrategy:()=>Hw,createGooglePayBraintreeButtonStrategy:()=>Vw,createGooglePayCheckoutComButtonStrategy:()=>Kw,createGooglePayCybersourceButtonStrategy:()=>Jw,createGooglePayOrbitalButtonStrategy:()=>Zw,createGooglePayPayPalCommerceButtonStrategy:()=>Gw,createGooglePayStripeButtonStrategy:()=>Xw,createGooglePayTdOnlineMartButtonStrategy:()=>eI,createGooglePayWorldpayAccessButtonStrategy:()=>Qw,createLinkV2ButtonStrategy:()=>fI,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>hI,createPayPalCommerceButtonStrategy:()=>nI,createPayPalCommerceCreditButtonStrategy:()=>aI,createPayPalCommerceVenmoButtonStrategy:()=>cI,createPaypalExpressButtonStrategy:()=>yI});class Ze 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"}(We||(We={}));class Xe extends Ze{constructor(e){super(function(e){switch(e){case We.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case We.MissingCart:return"Unable to proceed because cart data is unavailable.";case We.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case We.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case We.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case We.MissingCheckoutConfig:case We.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case We.MissingOrder:return"Unable to proceed because order data is unavailable.";case We.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case We.MissingPayment:return"Unable to proceed because payment data is unavailable.";case We.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case We.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case We.MissingPaymentProviderCustomer:return"Unable to proceed because payment provider customer is unavailable.";case We.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"}(Ye||(Ye={}));class Qe extends Ze{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 et;class tt{constructor(e,t){this._requestSender=e,this._subscriptionActionCreator=t}continueAsGuest(e,t){return i=>{const n=i.getState(),r=n.checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);const o=n.customer.getCustomer();if(o&&!o.isGuest)throw new Qe;const a=n.billingAddress.getBillingAddress();let s;if(a){const{country:t}=a,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(a,["country"]);s=Object.assign(Object.assign({},i),e)}else s=e;const d=!E(a);return he(se(me(l(Ye.ContinueAsGuestRequested)),de(()=>{return e=this,i=void 0,o=function*(){const{body:e}=yield this._createOrUpdateBillingAddress(r.id,s,d,t);return l(Ye.ContinueAsGuestSucceeded,e)},new((n=void 0)||(n=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 i;e.done?t(e.value):(i=e.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((o=o.apply(e,i||[])).next())});var e,i,n,o})).pipe(ge(e=>Je(Ye.ContinueAsGuestFailed,e))),this._updateCustomerConsent(e,t))}}updateAddress(e,t){return i=>oe.create(n=>{const r=i.getState(),o=r.checkout.getCheckout();if(!o)throw new Xe(We.MissingCheckout);n.next(l(Ye.UpdateBillingAddressRequested));const a=r.billingAddress.getBillingAddress(),s=!E(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})=>{n.next(l(Ye.UpdateBillingAddressSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Ye.UpdateBillingAddressFailed,e))})})}_updateCustomerConsent({email:e,acceptsAbandonedCartEmails:t,acceptsMarketingNewsletter:i},n){return null==t&&null==i?ce():this._subscriptionActionCreator.updateSubscriptions({email:e,acceptsMarketingNewsletter:i||!1,acceptsAbandonedCartEmails:t||!1},n)}_createOrUpdateBillingAddress(e,t,i,n){return i?this._requestSender.updateAddress(e,t,n):this._requestSender.createAddress(e,t,n)}}class it extends Ze{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"}(et||(et={}));const nt=et,rt={"X-Checkout-SDK-Version":"1.864.0"};const ot={include:["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"].join(",")};class at{constructor(e){this._requestSender=e}createAddress(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/billing-address`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(n,{body:t,params:ot,headers:r,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}updateAddress(e,t,{timeout:i}={}){const{id:n}=t,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(t,["id"]),o=`/api/storefront/checkouts/${e}/billing-address/${n}`,a=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.put(o,{params:ot,body:r,headers:a,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}}var st,dt;function ct(e,t){const i=u((e,t)=>t.type===st.Synchronize?t.payload:e,e.getState(),{stateTransformer:t});return e.subscribe(e=>{i.dispatch(l(st.Synchronize,e))},{initial:!1}),i}!function(e){e.Synchronize="SYNCHRONIZE"}(st||(st={}));class lt{log(e){console.error(e)}}!function(e){e.ClearError="CLEAR_ERROR"}(dt||(dt={}));class ut{clearError(e){return{type:dt.ClearError,payload:e}}}function ht(){try{return"production"}catch(e){return"development"}}class pt{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 mt{log(){}info(){}warn(){}error(){}debug(){}}const yt=function(e=!0){return e?new pt(console):new mt}("test"!==ht());function gt(){return yt}function vt(e,t,i){const n=new WeakMap;function r(e){return(...i)=>{const r=i[i.length-1],{useCache:o}=(a=r)&&"boolean"==typeof a.useCache?r:{useCache:!1};var a;if(!o)return e.call(this,...i);const s=n.get(this)||{};var d;return n.get(this)||n.set(this,s),s[t]||(s[t]=(d=e,Pe(function(...e){const t=d.call(this,...e);return t instanceof oe?le(t).pipe(_e()):"function"==typeof t?Pe(e=>le(t(e)).pipe(_e()),{isEqual:A}):t},{isEqual:A}))),s[t].call(this,...i)}}return{get(){if("function"!=typeof i.value)throw new Error("Decorator should be used in functions");const e=r.call(this,i.value);return Object.defineProperty(this,t,Object.assign(Object.assign({},i),{value:e})),e}}}var ft;!function(e){e.LoadConfigRequested="LOAD_CONFIG_REQUESTED",e.LoadConfigSucceeded="LOAD_CONFIG_SUCCEEDED",e.LoadConfigFailed="LOAD_CONFIG_FAILED"}(ft||(ft={}));class St{constructor(e){this._configRequestSender=e}loadConfig(e){return oe.create(t=>{t.next(l(ft.LoadConfigRequested)),this._configRequestSender.loadConfig(e).then(e=>{t.next(l(ft.LoadConfigSucceeded,e.body)),t.complete()}).catch(e=>{t.error(h(ft.LoadConfigFailed,e))})})}}!function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);o>3&&a&&Object.defineProperty(t,i,a)}([vt],St.prototype,"loadConfig",null);const wt={body:{},headers:{},status:0};class It extends Ze{constructor(e,{message:t,errors:i}={}){const{body:n,headers:r,status:o}=e||wt;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=n,this.headers=r,this.status=o,this.errors=i||[]}}class _t extends It{constructor(e){super(e,{message:e.body.title}),this.name="CheckoutNotAvailableError",this.type="checkout_not_available"}}const Ct="This API endpoint is for internal use only and may change in the future";class bt{constructor(e){this._requestSender=e}loadConfig({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-settings",{timeout:e,headers:Object.assign({Accept:nt.JsonV1,"X-API-INTERNAL":Ct},rt),params:t}).catch(e=>{if(e.status>=400&&e.status<500)throw new _t(e);throw e})}}var Pt;!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"}(Pt||(Pt={}));class Ot{constructor(e){this._couponRequestSender=e}applyCoupon(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);n.next(l(Pt.ApplyCouponRequested)),this._couponRequestSender.applyCoupon(r.id,e,t).then(({body:e})=>{n.next(l(Pt.ApplyCouponSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Pt.ApplyCouponFailed,e))})})}removeCoupon(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);n.next(l(Pt.RemoveCouponRequested)),this._couponRequestSender.removeCoupon(r.id,e,t).then(({body:e})=>{n.next(l(Pt.RemoveCouponSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Pt.RemoveCouponFailed,e))})})}}const Et=["cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","customer.customerGroup","payments","promotions.banners"];var At,Tt,kt,Dt;function Mt(e){return te(e).join(",")}!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(At||(At={}));class zt{constructor(e){this._requestSender=e}applyCoupon(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/coupons`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(n,{headers:r,timeout:i,params:{include:Mt([...Et,At.AvailableShippingOptions])},body:{couponCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}removeCoupon(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/coupons/${t}`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.delete(n,{headers:r,timeout:i,params:{include:Mt([...Et,At.AvailableShippingOptions])}}).catch(e=>{if("empty_cart"===e.body.type)throw new it;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"}(Tt||(Tt={}));class Nt{constructor(e){this._giftCertificateRequestSender=e}applyGiftCertificate(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);n.next(l(Tt.ApplyGiftCertificateRequested)),this._giftCertificateRequestSender.applyGiftCertificate(r.id,e,t).then(({body:e})=>{n.next(l(Tt.ApplyGiftCertificateSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Tt.ApplyGiftCertificateFailed,e))})})}removeGiftCertificate(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);n.next(l(Tt.RemoveGiftCertificateRequested)),this._giftCertificateRequestSender.removeGiftCertificate(r.id,e,t).then(({body:e})=>{n.next(l(Tt.RemoveGiftCertificateSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Tt.RemoveGiftCertificateFailed,e))})})}}class xt{constructor(e){this._requestSender=e}applyGiftCertificate(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/gift-certificates`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(n,{headers:r,timeout:i,params:{include:Mt(Et)},body:{giftCertificateCode:t}}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}removeGiftCertificate(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/gift-certificates/${t}`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.delete(n,{headers:r,timeout:i,params:{include:Mt(Et)}}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}}function Ft(e){return e&&"resolveIds"in e}function Rt(e,t){return Object.assign(e,{resolveIds:t})}class Lt extends Ze{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class Bt{constructor(e){var t,i,n;this._factories={},this._instances={},this._defaultToken=null!==(t=null==e?void 0:e.defaultToken)&&void 0!==t?t:"default",this._useFallback=null===(i=null==e?void 0:e.useFallback)||void 0===i||i,this._tokenResolver=null!==(n=null==e?void 0:e.tokenResolver)&&void 0!==n?n: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 i=this._tokenResolver(e,Object.keys(this._factories),t);return i?this._factories[i]:void 0}register(e,t){if(this._hasFactory(e))throw new Lt(`'${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 i=this.getFactory(e);if(!i)throw new Lt(`'${e}' is not registered.`);this._instances[t]=i()}return this._instances[t]}}class jt{constructor(e=!1){this._useFallback=e,this._registry=new Bt({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,i){var n;const r=this._decodeToken(e),o=[];t.forEach(e=>{const t=this._decodeToken(e),i={token:e,matches:0,default:!1};for(const[e,n]of Object.entries(t)){if(e in r&&r[e]!==n){i.matches=0;break}e in r&&r[e]===n&&i.matches++,"default"===e&&!0===n&&(i.default=!0)}o.push(i)});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"===ht()&>().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=a[0];if(i&&(null==s?void 0:s.matches)!==Object.keys(r).length)throw new Error("Unable to resolve to a registered token with the provided token.");if(s&&s.token)return s.token;if(this._useFallback){const e=null===(n=o.find(e=>e.default))||void 0===n?void 0:n.token;if(e)return e}throw new Error("Unable to resolve to a registered token with the provided token.")}}function Ut(e){const t=e;return"object"==typeof t&&"object"==typeof t.payload&&"string"==typeof t.payload.token}!function(e){e.BuyNow="BUY_NOW"}(kt||(kt={})),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"}(Dt||(Dt={}));var qt,Vt,Gt;class Ht{constructor(e,t,i){this._customerRequestSender=e,this._checkoutActionCreator=t,this._spamProtectionActionCreator=i}createCustomer(e,t){return i=>{const n=i.getState().config.getStoreConfigOrThrow(),{isStorefrontSpamProtectionEnabled:r}=n.checkoutSettings,o=n=>le(this._customerRequestSender.createAccount(Object.assign(Object.assign({},e),{token:n}),t)).pipe(Ce(()=>se(this._checkoutActionCreator.loadCurrentCheckout(t)(i),me(l(Dt.CreateCustomerSucceeded)))));return se(me(l(Dt.CreateCustomerRequested)),r?le(this._spamProtectionActionCreator.execute()(i)).pipe(Ce(e=>{var t;return Ut(e)?se(me(e),o(null===(t=e.payload)||void 0===t?void 0:t.token)):me(e)})):o()).pipe(ge(e=>Je(Dt.CreateCustomerFailed,e)))}}createAddress(e,t){return se(me(l(Dt.CreateCustomerAddressRequested)),de(()=>{return i=this,n=void 0,o=function*(){const{body:i}=yield this._customerRequestSender.createAddress(e,t);return l(Dt.CreateCustomerAddressSucceeded,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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).pipe(ge(e=>Je(Dt.CreateCustomerAddressFailed,e)))}signInCustomer(e,t){return i=>{const n=i.getState().checkout.getCheckoutOrThrow(),r=n.cart.source===kt.BuyNow?n.id:void 0;return se(me(l(Dt.SignInCustomerRequested)),le(this._customerRequestSender.signInCustomer(Object.assign(Object.assign({},e),{cartId:r}),t)).pipe(Ce(({body:e})=>e.data.persistentCartRetrievalInformation?se(this._checkoutActionCreator.loadCheckout(e.data.persistentCartRetrievalInformation.id,t)(i),me(l(Dt.SignInCustomerSucceeded,e.data))):se(this._checkoutActionCreator.loadCurrentCheckout(t)(i),me(l(Dt.SignInCustomerSucceeded,e.data)))))).pipe(ge(e=>Je(Dt.SignInCustomerFailed,e)))}}signOutCustomer(e){return t=>{const i=t.getState().checkout.getCheckoutOrThrow(),n=i.cart.source===kt.BuyNow?i.id:void 0;return se(me(l(Dt.SignOutCustomerRequested)),le(this._customerRequestSender.signOutCustomer(e,n)).pipe(Ce(({body:i})=>se(this._checkoutActionCreator.loadCurrentCheckout(e)(t),me(l(Dt.SignOutCustomerSucceeded,i.data)))))).pipe(ge(e=>Je(Dt.SignOutCustomerFailed,e)))}}}class $t{constructor(e){this._requestSender=e}createAccount(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer",{timeout:t,headers:rt,body:e})}createAddress(e,{timeout:t}={}){return this._requestSender.post("/api/storefront/customer-address",{timeout:t,headers:rt,body:e})}signInCustomer(e,{timeout:t}={}){return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:t,headers:rt,body:e})}signOutCustomer({timeout:e}={},t){return this._requestSender.delete("/internalapi/v1/checkout/customer",Object.assign({timeout:e,headers:rt},t&&{body:{cartId:t}}))}}function Wt(e,t,i=!0){var n;return null!==(n=e[t])&&void 0!==n?n:i}function Yt(e,t,i){t.forEach(t=>{Ft(t)&&t.resolveIds.forEach(n=>{if(e.getFactory(n,!0))return;const r=Rt(()=>t(i),t.resolveIds);e.register(n,r)})})}function Kt(e,t,i,n){const r=e.getFactory(i);if(!r)return;if(!t.some(e=>Jt(r,e))){const e=`A different strategy is registered for ${JSON.stringify(i)}.`;return new Error(e)}const o=new jt(e.getUseFallback());Yt(o,t,n);const a=o.getFactory(i);if(!a||!Jt(a,r)){const e=`A different strategy is resolved for ${JSON.stringify(i)}.`;return new Error(e)}}function Jt(e,t){return Ft(e)&&Ft(t)&&A(e.resolveIds,t.resolveIds)}!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"}(qt||(qt={}));class Zt{constructor(e,t,i,n){this._strategyRegistry=e,this._strategyRegistryV2=t,this._paymentIntegrationService=i,this._errorLogger=n}signIn(e,t){return oe.create(i=>{const n=t&&t.methodId,r={methodId:n};i.next(l(qt.SignInRequested,void 0,r)),this._getStrategy(n).signIn(e,t).then(()=>{i.next(l(qt.SignInSucceeded,void 0,r)),i.complete()}).catch(e=>{i.error(h(qt.SignInFailed,e,r))})})}signOut(e){return oe.create(t=>{const i=e&&e.methodId,n={methodId:i};t.next(l(qt.SignOutRequested,void 0,n)),this._getStrategy(i).signOut(e).then(()=>{t.next(l(qt.SignOutSucceeded,void 0,n)),t.complete()}).catch(e=>{t.error(h(qt.SignOutFailed,e,n))})})}executePaymentMethodCheckout(e){return oe.create(t=>{const i=e&&e.methodId,n={methodId:i};t.next(l(qt.ExecutePaymentMethodCheckoutRequested,void 0,n)),this._getStrategy(i).executePaymentMethodCheckout(e).then(()=>{t.next(l(qt.ExecutePaymentMethodCheckoutSucceeded,void 0,n)),t.complete()}).catch(e=>{t.error(h(qt.ExecutePaymentMethodCheckoutFailed,e,n))})})}initialize(e){return t=>oe.create(i=>{var n,r;const o=t.getState(),a=e&&e.methodId,s={methodId:a},{features:d}=o.config.getStoreConfigOrThrow().checkoutSettings;if(Wt(d,"CHECKOUT-9450.lazy_load_payment_strategies",!1)){const t={id:a||""},i=Kt(this._strategyRegistryV2,null!==(n=null==e?void 0:e.integrations)&&void 0!==n?n:[],t,this._paymentIntegrationService);i&&this._errorLogger.log(i),Yt(this._strategyRegistryV2,null!==(r=null==e?void 0:e.integrations)&&void 0!==r?r:[],this._paymentIntegrationService)}if(a&&o.customerStrategies.isInitialized(a))return i.complete();i.next(l(qt.InitializeRequested,void 0,s)),this._getStrategy(a).initialize(e).then(()=>{i.next(l(qt.InitializeSucceeded,void 0,s)),i.complete()}).catch(e=>{i.error(h(qt.InitializeFailed,e,s))})})}deinitialize(e){return t=>oe.create(i=>{const n=t.getState(),r=e&&e.methodId,o={methodId:r};if(r&&!n.customerStrategies.isInitialized(r))return i.complete();i.next(l(qt.DeinitializeRequested,void 0,o)),this._getStrategy(r).deinitialize(e).then(()=>{i.next(l(qt.DeinitializeSucceeded,void 0,o)),i.complete()}).catch(e=>{i.error(h(qt.DeinitializeFailed,e,o))})})}widgetInteraction(e,t){return oe.create(i=>{const n={methodId:t&&t.methodId};i.next(l(qt.WidgetInteractionStarted,void 0,n)),e().then(()=>{i.next(l(qt.WidgetInteractionFinished,void 0,n)),i.complete()}).catch(e=>{i.error(h(qt.WidgetInteractionFailed,e,n))})})}_getStrategy(e){let t;try{t=this._strategyRegistryV2.get({id:e||""})}catch(i){t=this._strategyRegistry.get(e)}return t}}function Xt(e,t=[]){return Array.isArray(t)?Mt([...e,...t]):function(e,t){const i=R(Y(t,e=>!e)),n=R(f(t));return Mt([...g(e,i),...n])}(e,t)}class Qt{constructor(e){this._requestSender=e}loadCheckout(e,{params:{include:t}={},timeout:i}={}){const n=`/api/storefront/checkout/${e}`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.get(n,{params:{include:Xt(Et,t)},headers:r,timeout:i}).catch(e=>{if(e.status>=400&&e.status<500)throw new _t(e);throw e})}updateCheckout(e,t,{params:{include:i}={},timeout:n}={}){const r=`/api/storefront/checkout/${e}`,o=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.put(r,{params:{include:Xt(Et,i)},body:t,headers:o,timeout:n}).catch(e=>{if("empty_cart"===e.body.type)throw new it;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"}(Vt||(Vt={})),function(e){e.HydrateInitialState="HYDRATE_INITIAL_STATE"}(Gt||(Gt={}));var ei;class ti{constructor(e,t,i){this._checkoutRequestSender=e,this._configActionCreator=t,this._formFieldsActionCreator=i}loadCheckout(e,t){return()=>se(me(l(Vt.LoadCheckoutRequested)),he(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})),de(()=>this._checkoutRequestSender.loadCheckout(e,t).then(({body:e})=>l(Vt.LoadCheckoutSucceeded,this._transformCustomerAddresses(e))))).pipe(ge(e=>Je(Vt.LoadCheckoutFailed,e)))}loadDefaultCheckout(e){return t=>se(me(l(Vt.LoadCheckoutRequested)),he(this._configActionCreator.loadConfig({useCache:!0,timeout:null==e?void 0:e.timeout}),this._formFieldsActionCreator.loadFormFields({useCache:!0,timeout:null==e?void 0:e.timeout})),de(()=>{return i=this,n=void 0,o=function*(){const i=t.getState().config.getContextConfig();if(!i||!i.checkoutId)throw new Xe(We.MissingCheckoutConfig);const{body:n}=yield this._checkoutRequestSender.loadCheckout(i.checkoutId,e);return l(Vt.LoadCheckoutSucceeded,this._transformCustomerAddresses(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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).pipe(ge(e=>Je(Vt.LoadCheckoutFailed,e)))}updateCheckout(e,t){return i=>new oe(n=>{const r=i.getState().checkout.getCheckout();if(!r)throw new Xe(We.MissingCheckout);n.next(l(Vt.UpdateCheckoutRequested)),this._checkoutRequestSender.updateCheckout(r.id,e,t).then(({body:e})=>{n.next(l(Vt.UpdateCheckoutSucceeded,e)),n.complete()}).catch(e=>{n.error(h(Vt.UpdateCheckoutFailed,e))})})}loadCurrentCheckout(e){return t=>{const i=t.getState().checkout.getCheckout();if(!i)throw new Xe(We.MissingCheckout);return this.loadCheckout(i.id,e)(t)}}hydrateInitialState(e){return{type:Gt.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"}(ei||(ei={}));var ii;class ni{constructor(e){this._formFieldsRequestSender=e}loadFormFields(e){return se(me(l(ei.LoadFormFieldsRequested)),de(()=>{return t=this,i=void 0,r=function*(){const{body:t}=yield this._formFieldsRequestSender.loadFields(e);return l(ei.LoadFormFieldsSucceeded,t)},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r})).pipe(ge(e=>Je(ei.LoadFormFieldsFailed,e)))}}!function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);o>3&&a&&Object.defineProperty(t,i,a)}([vt],ni.prototype,"loadFormFields",null);class ri{constructor(e){this._requestSender=e}loadFields({timeout:e}={}){return this._requestSender.get("/api/storefront/form-fields",{timeout:e,headers:Object.assign({Accept:nt.JsonV1,"X-API-INTERNAL":Ct},rt)})}}class oi extends Ze{constructor(){super("You haven't complete our spam protection challenge. Please try again."),this.name="SpamProtectionChallengeNotCompletedError",this.type="spam_protection_challenge_not_completed"}}class ai extends Ze{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"}(ii||(ii={}));var si,di,ci,li=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ui{constructor(e,t){this._googleRecaptcha=e,this._requestSender=t}initialize(e){return t=>se(me(l(ii.InitializeRequested,void 0)),de(()=>li(this,void 0,void 0,function*(){const i=e?e.containerId:"spamProtectionContainer";if(document.getElementById(i)&&this._googleRecaptcha.reset(i),!e&&!document.getElementById(i)){const e=document.createElement("div");e.setAttribute("id",i),document.body.appendChild(e)}const n=t.getState().config.getStoreConfigOrThrow().checkoutSettings.googleRecaptchaSitekey;return yield this._googleRecaptcha.load(i,n),l(ii.InitializeSucceeded)}))).pipe(ge(e=>Je(ii.InitializeFailed,e)))}verifyCheckoutSpamProtection(){return e=>de(()=>{const t=e.getState().checkout.getCheckout();if(!t)throw new Xe(We.MissingCheckout);return se(me(l(ii.VerifyCheckoutRequested)),le(this.execute()(e)).pipe(Ce(e=>Ut(e)&&e.payload?le(this._requestSender.validate(t.id,e.payload.token)).pipe(Ce(({body:t})=>se(me(e),me(l(ii.VerifyCheckoutSucceeded,t))))):me(e)))).pipe(ge(e=>Je(ii.VerifyCheckoutFailed,e)))})}execute(){return e=>se(me(l(ii.ExecuteRequested)),this.initialize()(e),this._googleRecaptcha.execute().pipe(be(1)).pipe(Ce(({error:e,token:t})=>li(this,void 0,void 0,function*(){if(e instanceof oi)throw e;if(e||!t)throw new ai;return l(ii.ExecuteSucceeded,{token:t})})))).pipe(ge(e=>Je(ii.ExecuteFailed,e)))}}class hi{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"}(si||(si={}));class pi extends Ze{constructor(e){super(function(e){switch(e){case si.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case si.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case si.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case si.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 mi extends Ze{constructor(){super("Spam protection is not loaded. Please try again."),this.name="SpamProtectionNotLoadedError",this.type="spam_protection_failed"}}class yi{constructor(e,t){this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=Pe((e,t,i)=>{const n=new ae;if(!i)throw new Error;return this._widgetId=e.render(i.id,{sitekey:t,size:"invisible",callback:()=>{n.next({token:e.getResponse(this._widgetId)}),e.reset(this._widgetId)},"error-callback":()=>{n.next({error:new ai})}}),n},{isEqual:(e,t)=>e===t})}load(e,t){return this.googleRecaptchaScriptLoader.load().then(i=>{i&&(this._event$=this._memoized(i,t,document.getElementById(e)),this._recaptcha=i)}).catch(e=>{throw e})}reset(e){var t;const i=document.getElementById(e);null==i||i.remove(),null===(t=this._recaptcha)||void 0===t||t.reset(this._widgetId)}execute(){return de(()=>{const e=this._event$,t=this._recaptcha;if(!e||!t)throw new pi(si.SpamProtectionNotInitialized);return de(()=>{const e=document.querySelector('iframe[src*="bframe"]');return e?me(e):ye(new mi)}).pipe(Ie(e=>e.pipe(ve(250),Ce((e,t)=>t<28?me(e):ye(e)))),Ce(i=>(this._watchRecaptchaChallengeWindow(e,i),t.execute(this._widgetId),e)),ge(e=>me({error:e})))})}_watchRecaptchaChallengeWindow(e,t){const i=t.parentElement;if(!i)throw new mi;const n=i.parentElement;if(!n)throw new mi;this.mutationObserverFactory.create(()=>{"hidden"===n.style.visibility&&e.next({error:new oi})}).observe(n,{attributes:!0,attributeFilter:["style"]})}}class gi{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((i,n)=>{this._window[e]=()=>i(this._window.grecaptcha),this._scriptLoader.loadScript(`//www.google.com/recaptcha/api.js?${t}`).catch(e=>{this._loadPromise=void 0,n(e)})})}}function vi(e){return new yi(new gi(e),new hi)}class fi{constructor(e){this._requestSender=e}validate(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/spam-protection`,r=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(n,{body:{token:t},headers:r,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}}class Si{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 wi(e){if(!/^(https?:)?\/\//.test(e))throw new Lt("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const i=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}${i?`:${i}`:""}`,pathname:t.pathname,port:i,protocol:t.protocol,search:t.search}}class Ii extends Ze{constructor(e){super(e||"Unable to proceed due to no extension configured for this region."),this.name="ExtensionNotFoundError",this.type="extension_not_found"}}function _i(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"}(di||(di={}));class Ci{constructor(e,t,i){this._targetWindow=t,this._context=i,this._targetOrigin="*"===e?"*":wi(e).origin}post(e,t){const i=this._targetWindow;if(window===i)return;if(!i)throw new Error("Unable to post message because target window is not set.");const n=t&&ue(window,"message").pipe(Se(e=>e.origin===this._targetOrigin&&_i(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),we(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),be(1)).toPromise();return i.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),n}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}function bi(e){var t;const i=null===(t=document.querySelector(`[data-extension-id="${e.id}"]`))||void 0===t?void 0:t.querySelector("iframe");if(!(null==i?void 0:i.contentWindow))throw new Ii(`Unable to post due to no extension rendered for ID: ${e.id}.`);return new Ci(e.url,i.contentWindow)}!function(e){e.ExtensionReady="EXTENSION:READY",e.ExtensionFailed="EXTENSION:FAILED"}(ci||(ci={}));class Pi{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}class Oi extends Ze{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 Ei;class Ai{constructor(e){this._mutationObserver=e}ensurePresence(e,t){return i=this,n=void 0,o=function*(){const i=new Pi(t),n=this._mutationObserver.create(t=>{t.forEach(t=>{0!==Array.from(t.removedNodes).filter(t=>e.some(e=>t===e||t.contains(e))).length&&i.cancel(new Oi)})});n.observe(document.body,{childList:!0,subtree:!0});try{const e=yield i.promise;return n.disconnect(),e}catch(e){throw n.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}function Ti(e,t){const{iframeResizer:i}=Ge(785);return i(e,t)}class ki extends Ze{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"}(Ei||(Ei={}));class Di{constructor(e){this._options=e}createFrame(e,t,i,n){const r=document.getElementById(t),{timeout:o=6e4}=this._options||{};if(!r)throw new ki("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,i,n).catch(e=>{throw r.removeChild(a),e})}_toResizableFrame(e,t,i,n){return r=this,o=void 0,s=function*(){const r=new Ai(new hi),o=new Promise((r,o)=>{const a=window.setTimeout(()=>{try{n()}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 ki("Unable to load the extension because the content could not be loaded."))},t),s=t=>{if(t.origin===wi(e.src).origin&&_i(t.data,Ei.ResizeIframe)){e.style.display="";const t=Ti({autoResize:!1,scrolling:!1,sizeWidth:!1,heightCalculationMethod:"bodyOffset",initCallback:i},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 i(e){try{d(s.next(e))}catch(e){t(e)}}function n(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(i,n)}d((s=s.apply(r,o||[])).next())});var r,o,a,s}}class Mi{constructor(e,t,i){this._containerId=e,this._extension=t,this._config=i;const{cartId:n,parentOrigin:r}=this._config;this._url=new URL(this._extension.url),this._url.searchParams.set("extensionId",this._extension.id),this._url.searchParams.set("cartId",n),this._url.searchParams.set("parentOrigin",r)}attach(){var e,t,i,n,r;return t=this,i=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 Di,i=e=>{bi(this._extension).post({type:e})};this._iframe=yield t.createFrame(this._url.toString(),this._containerId,()=>{i(ci.ExtensionReady)},()=>{i(ci.ExtensionFailed)});const n=document.getElementById(this._containerId);null==n||n.setAttribute("data-extension-id",this._extension.id)},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())})}detach(){this._iframe&&this._iframe.parentElement&&this._iframe.parentElement.removeChild(this._iframe)}}class zi{constructor(e){this._requestSender=e}loadExtensions(e){return()=>oe.create(t=>{t.next(l(di.LoadExtensionsRequested)),this._requestSender.loadExtensions(e).then(e=>{const i=e.body;t.next(l(di.LoadExtensionsSucceeded,i)),t.complete()}).catch(e=>{t.error(h(di.LoadExtensionsFailed,e))})})}renderExtension(e,t,i){return n=>oe.create(r=>{return o=this,a=void 0,d=function*(){const o=n.getState(),{id:a}=o.cart.getCartOrThrow(),{links:{checkoutLink:s},checkoutSettings:{features:d}}=o.config.getStoreConfigOrThrow();if(!d["PROJECT-5029.checkout_extension"])return r.complete();const c=o.extensions.getExtensionByRegion(t);try{if(!c)throw new Ii(`Unable to proceed due to no extension configured for the region: ${t}.`);if(r.next(l(di.RenderExtensionRequested)),"worker"===c.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")}}(c.url);i.add(c.id,e)}else{const t=new Mi(e,c,{cartId:a,parentOrigin:wi(s).origin});yield t.attach()}r.next(l(di.RenderExtensionSucceeded)),r.complete()}catch(e){r.error(h(di.RenderExtensionFailed,e))}},new((s=void 0)||(s=Promise))(function(e,t){function i(e){try{r(d.next(e))}catch(e){t(e)}}function n(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(i,n)}r((d=d.apply(o,a||[])).next())});var o,a,s,d})}}class Ni{constructor(e){this._requestSender=e}loadExtensions({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/checkout-extensions",{timeout:e,headers:Object.assign({Accept:nt.JsonV1},rt),params:t})}}const xi=function(e,t,i){return t&&i?Fi(0,t,i):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(i=>{const n=Object.getOwnPropertyDescriptor(e.prototype,i);n&&"constructor"!==i&&Object.defineProperty(t.prototype,i,Fi(e.prototype,i,n))}),t}(e)};function Fi(e,t,i){if("function"!=typeof i.value)return i;let n=i.value;return{get(){const e=n.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},i),{value:e})),e},set(e){n=e}}}var Ri,Li;class Bi{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 i=this._listeners[e];i||(this._listeners[e]=i=[]),-1===i.indexOf(t)&&i.push(t)}removeListener(e,t){const i=this._listeners[e];if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}trigger(e,t){const i=this._listeners[e.type];i&&i.forEach(i=>t?i(e,t):i(e))}_handleMessage(e){const t=e.data,{context:i}=t,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(t,["context"]);this.trigger(n,i)}}!function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);o>3&&a&&Object.defineProperty(t,i,a)}([xi],Bi.prototype,"_handleMessage",null);class ji{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 Ui extends Ze{constructor(e){super(e||"Unable to proceed due to unsupported extension command."),this.name="UnsupportedExtensionCommandError",this.type="unsupported_extension_command_error"}}class qi extends Ze{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"}(Ri||(Ri={})),function(e){e.GetConsignments="EXTENSION:GET_CONSIGNMENTS"}(Li||(Li={}));class Vi{constructor(e={},t={},i={}){this._workers=e,this._commandListeners=t,this._queryListeners=i}add(e,t){this._workers[e]=t}listenForCommand(e,t,i){const n=this._getWorkerById(e);this._commandListeners[e]||(this._commandListeners[e]=new Bi(n));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,n)=>{(null==n?void 0:n.extensionId)===e&&i(t,n)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,i){const n=this._getWorkerById(e);this._queryListeners[e]||(this._queryListeners[e]=new Bi(n));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,n)=>{(null==n?void 0:n.extensionId)===e&&i(t,n)};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 ji(this._workers[e],e).post(t)}clearCacheById(e){delete this._workers[e]}_getWorkerById(e){const t=this._workers[e];if(!t)throw new Ii(`Worker with extensionId ${e} not found`);return t}_validateCommand(e){if(Object.values(Ri).includes(e))return e;throw new Ui}_validateQuery(e){if(Object.values(Li).includes(e))return e;throw new qi}}function Gi(e){return wi(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,`www.${e.hostname}`))}var Hi;class $i{constructor(e){this._sourceOrigins=[wi(e).origin,Gi(wi(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 i=this._listeners[e];i||(this._listeners[e]=i=[]),-1===i.indexOf(t)&&i.push(t)}removeListener(e,t){const i=this._listeners[e];if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}trigger(e,t){const i=this._listeners[e.type];i&&i.forEach(i=>t?i(e,t):i(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!_i(e.data,e.data.type))return;const t=e.data,{context:i}=t,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(t,["context"]);this.trigger(n,i)}}!function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);o>3&&a&&Object.defineProperty(t,i,a)}([xi],$i.prototype,"_handleMessage",null);class Wi{constructor(e,t,i={},n={},r={}){this._store=e,this._workerExtensionMessenger=t,this._commandListeners=i,this._queryListeners=n,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,i){const n=this._getExtensionById(e);if("worker"===n.type)return this._workerExtensionMessenger.listenForCommand(e,t,i);this._commandListeners[e]||(this._commandListeners[e]=new $i(n.url));const r=this._commandListeners[e];r.listen();const o=this._validateCommand(t),a=(t,n)=>{(null==n?void 0:n.extensionId)===e&&i(t,n)};return r.addListener(o,a),()=>{r.removeListener(o,a)}}listenForQuery(e,t,i){const n=this._getExtensionById(e);if("worker"===n.type)return this._workerExtensionMessenger.listenForQuery(e,t,i);this._queryListeners[e]||(this._queryListeners[e]=new $i(n.url));const r=this._queryListeners[e];r.listen();const o=this._validateQuery(t),a=(t,n)=>{(null==n?void 0:n.extensionId)===e&&i(t,n)};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 i=this._getExtensionById(e);if("worker"===i.type)return void this._workerExtensionMessenger.post(e,t);this._posters[e]||(this._posters[e]=bi(i)),this._posters[e].post(t)}catch(i){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 i=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.id===e);if(!i)throw new Ii(`Unable to proceed due to no extension found for ID: ${e}.`);return i}_getExtensionByRegion(e){var t;this._getExtensions();const i=null===(t=this._extensions)||void 0===t?void 0:t.find(t=>t.region===e);if(!i)throw new Ii(`Unable to proceed due to no extension found for region: ${e}.`);return i}_getExtensions(){if(this._extensions)return;const{extensions:{getExtensions:e}}=this._store.getState();if(this._extensions=e(),!this._extensions)throw new Ii("Extension configurations not found.")}_validateCommand(e){if(Object.values(Ri).includes(e))return e;throw new Ui}_validateQuery(e){if(Object.values(Li).includes(e))return e;throw new qi}}class Yi{constructor(e,t,i){this._store=e,this._extensionMessenger=t,this._subscribers=i,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 $i(e.url);t.addListener(Ei.Subscribe,this._handleSubscribe.bind(this)),t.addListener(Ei.Unsubscribe,this._handleUnsubscribe.bind(this)),t.listen(),this._listeners[e.id]=t})}broadcast(e){var t;const{data:{getExtensions:i}}=this._store.getState();null===(t=i())||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 i,n;delete this._subscribed[t],Object.keys(this._subscribed).length||(null===(n=(i=this._unsubscribers)[e])||void 0===n||n.call(i),delete this._unsubscribers[e])}}!function(e){e.ConsignmentsChanged="EXTENSION:CONSIGNMENTS_CHANGED"}(Hi||(Hi={}));const Ki=(e,t)=>{var i;const{data:{getConsignments:n}}=e.getState();let r=null!==(i=n())&&void 0!==i?i:[];return e.subscribe(({data:{getConsignments:e}})=>{var i;const n=null!==(i=e())&&void 0!==i?i:[];n!==r&&(t.broadcast({type:Hi.ConsignmentsChanged,payload:{consignments:n,previousConsignments:r}}),r=n)},({data:{getConsignments:e}})=>e())};class Ji 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 Zi,Xi;!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"}(Zi||(Zi={}));class Qi extends Ji{constructor(e){super(function(e){switch(e){case Zi.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case Zi.MissingCart:return"Unable to proceed because cart data is unavailable.";case Zi.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case Zi.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case Zi.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case Zi.MissingCheckoutConfig:case Zi.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case Zi.MissingOrder:return"Unable to proceed because order data is unavailable.";case Zi.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case Zi.MissingPayment:return"Unable to proceed because payment data is unavailable.";case Zi.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case Zi.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case Zi.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 en(e){return t=e.lineItems.physicalItems.filter(e=>!e.addedByPromotion),K(t,(e,t)=>e+t.quantity,0);var t}function tn(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"}(Xi||(Xi={}));class nn extends Ji{constructor(e){super(function(e){switch(e){case Xi.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Xi.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Xi.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Xi.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 rn={de:"eu",jp:"fe",uk:"eu",us:"na"};var on,an,sn,dn,cn,ln;!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"}(on||(on={})),function(e){e.Home="Home",e.Product="Product",e.Cart="Cart",e.Checkout="Checkout",e.Other="Other"}(an||(an={})),function(e){e.USD="USD",e.EUR="EUR",e.GBP="GBP",e.JPY="JPY"}(sn||(sn={})),function(e){e.PayAndShip="PayAndShip",e.PayOnly="PayOnly"}(dn||(dn={})),function(e){e.Gold="Gold",e.LightGray="LightGray",e.DarkGray="DarkGray"}(cn||(cn={})),function(e){e.C0001="C0001"}(ln||(ln={}));var un=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class hn{constructor(e){this.amazonPayV2ScriptLoader=e}initialize(e){return un(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,i){this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${e}`,{amazonCheckoutSessionId:t,changeAction:i})}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(()=>un(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 un(this,void 0,void 0,function*(){return this.amazonPayV2SDK&&this.amazonPayV2SDK.Pay.signout(),Promise.resolve()})}renderAmazonPayButton({buttonColor:e,checkoutState:t,containerId:i,decoupleCheckoutInitiation:n=!1,methodId:r,options:o,placement:a,isButtonMicroTextDisabled:s=!1}){const d=document.querySelector(`#${i}`);if(!d)return;const{id:c}=d.appendChild(this.getButtonParentContainer());o&&s&&(o.design=ln.C0001);const l=null!=o?o:this.getAmazonPayV2ButtonOptions(t,r,a,n,e);return this.createButton(c,l),this.getButtonParentContainer()}updateBuyNowFlowFlag(e){this.isBuyNowFlow=Boolean(e)}isPh4Enabled(e,t){const i=!!e["PROJECT-3483.amazon_pay_ph4"],n=!!e["INT-6885.amazon_pay_ph4_us_only"];return i&&n?"US"===t:i}prepareRequestConfig(e,t,i){const{publicKeyId:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["publicKeyId"]);return Object.assign(Object.assign({createCheckoutSessionConfig:this.isEnvironmentSpecific(n)?r:e},t&&{estimatedOrderAmount:t}),i&&{productType:i})}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,i,n=!1,r=cn.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 Qi(Zi.MissingPaymentMethod);const{checkoutLanguage:p,checkoutSessionMethod:m,createCheckoutSessionConfig:y,extractAmazonCheckoutSessionId:g,ledgerCurrency:v,publicKeyId:f="",isButtonMicroTextDisabled:S}=h;if(!l||!v)throw new Qi(Zi.MissingPaymentMethod);const w=Object.assign({merchantId:l,ledgerCurrency:v,checkoutLanguage:p,placement:i,buttonColor:r},S?{design:ln.C0001}:{});if(this.isBuyNowFlow)return Object.assign(Object.assign({},w),{sandbox:!!u});const I=a();w.productType=I&&0===en(I)?dn.PayOnly:dn.PayAndShip;const{checkoutSettings:{features:_},storeProfile:{shopPath:C,storeCountryCode:b}}=d();if(this.isPh4Enabled(_,b)){if(!y)throw new Qi(Zi.MissingPaymentMethod);const e=null===(o=s())||void 0===o?void 0:o.outstandingBalance.toString(),t=null==I?void 0:I.currency.code,i=Object.assign({},w);let r;return this.isEnvironmentSpecific(f)?(i.publicKeyId=f,r=y):(i.sandbox=!!u,r=Object.assign(Object.assign({},y),{publicKeyId:f})),n||(i.createCheckoutSessionConfig=r),e&&t&&(i.estimatedOrderAmount={amount:e,currencyCode:t}),i}const P={method:m,url:`${C}/remote-checkout/${t}/payment-session`,extractAmazonCheckoutSessionId:g};return Object.assign(Object.assign({},w),{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 tn(e,()=>new nn(Xi.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 pn extends Ji{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 mn{constructor(e,t=window){this.scriptLoader=e,this.windowWithAmazonPay=t}load(e){return t=this,i=void 0,r=function*(){const{initializationData:t}=e,i=(null==t?void 0:t.region)||"us",n=rn[i];if(yield this.scriptLoader.loadScript(`https://static-${n}.payments-amazon.com/checkout.js`),!this.windowWithAmazonPay.amazon)throw new pn;return this.windowWithAmazonPay.amazon},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}function yn(){return new hn(new mn(a()))}class gn extends Ji{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class vn extends Ji{constructor(e){super(e||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var fn=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Sn{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return fn(this,void 0,void 0,function*(){const{methodId:t,amazonpay:i}=e;if(!t||!(null==i?void 0:i.container))throw new gn('Unable to proceed because "methodId" or "containerId" argument is not provided.');let n;try{n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}catch(e){yield this.paymentIntegrationService.loadPaymentMethod(t),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)}yield this.amazonPayV2PaymentProcessor.initialize(n),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:i.container,methodId:t,placement:an.Checkout})})}deinitialize(){return fn(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize()})}signIn(){throw new vn('In order to sign in via Amazon, the shopper must click on "Amazon Pay" button.')}signOut(e){return fn(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 wn=Rt(e=>new Sn(e,yn()),[{id:"amazonpay"}]),In="3.128.0",_n="3.123.2",Cn="3.106.0";class bn{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()||(Wt(t,"PAYPAL-5809.braintree_hosted_fields_fix_version")?In:Wt(t,"PAYPAL-5636.update_braintree_sdk_version")?_n:Cn)}getPreloadedSDKVersion(){const e=this.braintreeWindow.braintree;if(e){const t=S(Object.values(e),e=>!!e.VERSION);return null==t?void 0:t.VERSION}}}class Pn extends Ji{constructor(e){super(e||"Unsupported browser error"),this.name="UnsupportedBrowserError",this.type="unsupported_browser"}}var On,En,An,Tn,kn,Dn,Mn;function zn(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"}(On||(On={})),function(e){e.Completed="COMPLETED",e.Pending="PENDING",e.Failed="FAILED"}(En||(En={})),function(e){e.TRUSTLY="trustly"}(An||(An={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="cancelled",e.UNRECOGNIZED="unrecognized"}(Tn||(Tn={})),function(e){e.Customer="CUSTOMER",e.Merchant="MERCHANT",e.Network="NETWORK",e.Internal="INTERNAL",e.Unknown="UNKNOWN"}(kn||(kn={})),function(e){e.KountNotEnabled="DATA_COLLECTOR_KOUNT_NOT_ENABLED"}(Dn||(Dn={})),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"}(Mn||(Mn={}));var Nn,xn,Fn,Rn=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ln{constructor(e){this.braintreeScriptLoader=e}initialize(e){this.setClientToken(e)}deinitialize(){return Rn(this,void 0,void 0,function*(){yield this.teardownModule(this.dataCollector),this.dataCollector=void 0})}getClient(){return Rn(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 Rn(this,void 0,void 0,function*(){const t={deviceData:void 0,teardown:()=>Promise.resolve()};if(!this.dataCollector)try{const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadDataCollector(),n=Object.assign({client:t,kount:!0},e);this.dataCollector=yield i.create(n)}catch(e){if(zn(e)&&e.code===Dn.KountNotEnabled)return t;throw e}return this.dataCollector})}getBraintreeGooglePayment(){return Rn(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 Rn(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 Rn(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment){const[t,i]=yield Promise.all([this.getClient(),this.braintreeScriptLoader.loadLocalPayment()]);this.braintreeLocalPayment=yield new Promise((n,r)=>{i.create({client:t,merchantAccountId:e},(e,t)=>{e&&r(e),n(t)})})}return this.braintreeLocalPayment})}getUsBankAccount(){return Rn(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 Rn(this,void 0,void 0,function*(){return this.visaCheckoutSDK||(this.visaCheckoutSDK=yield this.braintreeScriptLoader.loadVisaCheckoutSdk(e)),this.visaCheckoutSDK})}getVenmoCheckoutOrThrow(){return Rn(this,void 0,void 0,function*(){if(!this.braintreeVenmo){const e=yield this.getClient(),t=yield this.braintreeScriptLoader.loadVenmoCheckout(),i={client:e,allowDesktop:!0,paymentMethodUsage:"multi_use"},n=yield t.create(i);if(!n.isBrowserSupported())throw new Pn;this.braintreeVenmo=n}return this.braintreeVenmo})}setClientToken(e){this.clientToken=e}getClientTokenOrThrow(){if(!this.clientToken)throw new nn(Xi.PaymentNotInitialized);return this.clientToken}teardownModule(e){return e?e.teardown():Promise.resolve()}}!function(e){e.Sandbox="sandbox",e.Production="production"}(Nn||(Nn={})),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"}(xn||(xn={})),function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(Fn||(Fn={}));const Bn={[Cn]:{[xn.Client]:"sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt",[xn.PaypalCheckout]:"sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O",[xn.Paypal]:"sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+",[xn.LocalPayment]:"sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT",[xn.DataCollector]:"sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV",[xn.UsBankAccount]:"sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ",[xn.GooglePayment]:"sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe",[xn.ThreeDSecure]:"sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB",[xn.VisaCheckout]:"sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT",[xn.Venmo]:"sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov",[xn.HostedFields]:"sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy",[xn.Fastlane]:"sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa"},[_n]:{[xn.Client]:"sha384-o+nbQGcwNNxIBeXeu3+XmbSq+Cg8R3EN3N0l5hXCgMMU2RGY0t1z0LroSEIAbfAO",[xn.PaypalCheckout]:"sha384-WrfbWPBS4mH86GAoycPSgiH8hQ8KH7A67C93Hjhunv/xhNk2YpBn3wbFA4Fhg9U/",[xn.Paypal]:"sha384-VF389nvvrRUgDsTXMxTYORDtVegB9IQa3Cxr//DyJnLYnz8/X8VCzEvck2c+Megt",[xn.LocalPayment]:"sha384-tZKx2rEQbfmZpoPSY5VPmJEhaq4X75dLvwHMs3VE9U+C8lPyw+hWTIL1+GPvWCIH",[xn.DataCollector]:"sha384-E6k3wOpP7syCDDwaRDLF06942Y00NkbwJvWi2OQXwwKzGwG5fd3E7RFUvCCecfvO",[xn.UsBankAccount]:"sha384-258FON8LZGG0W9Qaz4Jij83pZHu30YnKjJA7gNulLBh6CclkucgF+tHDQuYFRYfW",[xn.GooglePayment]:"sha384-taJ2p/0+n0VH328POAoBiuEbL3tnHUTE9S42hK1V+Txs3X+QYjZOyKW35JgHRFfO",[xn.ThreeDSecure]:"sha384-+NSZH4Zj3sO5bdWvPKhU5N16QDxeueTVTnUVeleeESkhLSaz4Ob1hh/5myecc9Ym",[xn.VisaCheckout]:"sha384-66DiBjghxk1OmBj8aksN8gbQ+CwoQcx1vPfiXUN08g1iQVM+BwewF0p7toM3i7SS",[xn.Venmo]:"sha384-B5UwY42kE4RoLoWbQ7YpqosUlUad2/DlGWiw0HhoZbSPk30CQAaSA10ohyLDTkDU",[xn.HostedFields]:"sha384-Aw9EesSaUeWxe36PqEHiOyOyOq8M6CIb1gw7/yHNVPRzGtFXXcd2OQ8qXrIlOj2P",[xn.Fastlane]:"sha384-rhBL1hpZ71JqG+2TsT0Dih47mbjx8cjJCpeZjk9tw3df1gFMKfCTmMyZunhr7H4Y"},[In]:{[xn.Client]:"sha384-0WNxksIpRP+fYZiIdr12g6DBUQfLDzYCQJZtR/C8KkcwSGhPHfcFp3tTaGcMyFTq",[xn.PaypalCheckout]:"sha384-lWM1jk4BOxoDNV6Kop7tVNvQgINlmEVz0c/OwM+HNHK3QC8xqwd54Ovrt2QRDTjh",[xn.Paypal]:"sha384-fXUmVxC2EMZBDXZ7eTHSTL/LFBrHej/MSXT/vTBXvra4lzgLNGvREAp+x0GYObuH",[xn.LocalPayment]:"sha384-pha1xGuGSkmZH5x9aqHvRaO4xLea7rmQ/79PFj9zxNzxuFcOWZg7gOP7FibygOEC",[xn.DataCollector]:"sha384-Q6PI2F9eekWbAxhroybl+aEcvqhdowN/EQlGwBUyJOzPFn9982u9xl6SU6XfGKzc",[xn.UsBankAccount]:"sha384-W3RLQSKJL1tQ3+Y7mP6tmkamtZ8bV4Yw/XxL9Jj5JtXHraD8loMF8hAIG5m2zK7F",[xn.GooglePayment]:"sha384-TITQMsFWA3elDNGP2mWz2oKBo4qjt+TlqzovcaPoeBiAh/wPBi6nae50ADdgU1/i",[xn.ThreeDSecure]:"sha384-YiycYN89ZlL/Evcaq4y1ajW1mhd7JYfZBDuOwHtIn4/Jnm20GL+/XCM+zYAwWD8D",[xn.VisaCheckout]:"sha384-/OdaTv9qrkKzjObtUe6yzfDhHozFW/+uXlrSl736sOZRJpjGQETvpYXqMFFg69xv",[xn.Venmo]:"sha384-dA+ojdW9vbJS4JavcXyOs9d5uZHJg5dNtYupoPSH2zsXIiYDVS5amLb/u8qmQ6oz",[xn.HostedFields]:"sha384-31ZkS58+iaWsW06ftW52zzVZFp43WPd7pNYRiddYynSNg6Oh7WGbSFGorAUH6T1z",[xn.Fastlane]:"sha384-jlbrwNvL3HvLAUCtLSmrnQ2GH1udCUrRS/bVmReAS5fuIVvcW8Pko/Gkg82tlgtr"}};var jn,Un=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class qn{constructor(e,t,i){this.scriptLoader=e,this.braintreeHostWindow=t,this.braintreeSDKVersionManager=i}loadClient(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.Client,"client.min.js")})}loadFastlane(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.Fastlane,"fastlane.min.js")})}loadPaypalCheckout(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.PaypalCheckout,"paypal-checkout.min.js")})}loadPaypal(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.Paypal,"paypal.min.js")})}loadLocalPayment(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.LocalPayment,"local-payment.min.js")})}loadDataCollector(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.DataCollector,"data-collector.min.js")})}loadUsBankAccount(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.UsBankAccount,"us-bank-account.min.js")})}loadGooglePayment(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.GooglePayment,"google-payment.min.js")})}load3DS(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.ThreeDSecure,"three-d-secure.min.js")})}loadVisaCheckout(){return this.loadBraintreeModuleOrThrow(xn.VisaCheckout,"visa-checkout.min.js")}loadVenmoCheckout(){return this.loadBraintreeModuleOrThrow(xn.Venmo,"venmo.min.js")}loadHostedFields(){return Un(this,void 0,void 0,function*(){return this.loadBraintreeModuleOrThrow(xn.HostedFields,"hosted-fields.min.js")})}loadVisaCheckoutSdk(e){return Un(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 pn;return this.braintreeHostWindow.V})})}loadBraintreeModuleOrThrow(e,t){return Un(this,void 0,void 0,function*(){let i=this.getBraintreeModule(e);if(i)return i;const n=this.braintreeSDKVersionManager.getSDKVersion(),r=`//js.braintreegateway.com/web/${n}/js/${t}`,o=n in Bn?this.getIntegrityValuesByModuleName(e,n):void 0;if(yield this.scriptLoader.loadScript(r,o?{async:!0,attributes:{integrity:o,crossorigin:"anonymous"}}:void 0),i=this.getBraintreeModule(e),!i)throw new pn;return i})}getBraintreeModule(e){var t;return null===(t=this.braintreeHostWindow.braintree)||void 0===t?void 0:t[e]}getIntegrityValuesByModuleName(e,t){const i=Bn[t][e];if(!i)throw new Error("Unexpected fileName value");return i}}class Vn extends Ji{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}!function(e){e.BRAINTREE="braintree",e.BRAINTREE_FASTLANE="braintreeacceleratedcheckout"}(jn||(jn={}));var Gn,Hn=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(Gn||(Gn={}));class $n{constructor(e,t,i,n,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=i,this._braintreeSdk=n,this._applePayScriptLoader=r,this._onAuthorizeCallback=V,this._onError=V,this._onClick=V,this._subTotalLabel=Gn.Subtotal,this._shippingLabel=Gn.Shipping,this._hasApplePaySession=!1}initialize(e){var t;return Hn(this,void 0,void 0,function*(){const{methodId:i,applepay:n}=e;if(!i||!n)throw new Qi(Zi.MissingPaymentMethod);const{container:r,shippingLabel:o,subtotalLabel:a,onError:s=V,onClick:d=V,onPaymentAuthorize:c}=n;this._shippingLabel=o||Gn.Shipping,this._subTotalLabel=a||Gn.Subtotal,this._onAuthorizeCallback=c,this._onError=s,this._onClick=d;let l=this._paymentIntegrationService.getState();yield this._applePayScriptLoader.loadSdk();try{this._paymentMethod=l.getPaymentMethodOrThrow(i)}catch(e){l=yield this._paymentIntegrationService.loadPaymentMethod(i),this._paymentMethod=l.getPaymentMethodOrThrow(i)}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)===jn.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken)})}deinitialize(){return Promise.resolve()}signIn(){throw new vn('In order to sign in via Apple, the shopper must click on "Apple Pay" button.')}signOut(){throw new vn("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 gn("Unable to create sign-in button without valid container ID.");const i=this._createApplePayButtonElement();return t.appendChild(i),i}_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(),i=t.getCartOrThrow(),n=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new Qi(Zi.MissingPaymentMethod);const o=this._getBaseRequest(i,r,n,this._paymentMethod),a=this._sessionFactory.create(o);this._handleApplePayEvents(a,this._paymentMethod,n),a.begin(),this._hasApplePaySession=!0}_getBaseRequest(e,t,i,n){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=i,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=n,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,i){e.onvalidatemerchant=i=>Hn(this,void 0,void 0,function*(){try{const{body:n}=yield this._onValidateMerchant(t,i);e.completeMerchantValidation(n)}catch(e){this._onError(e)}}),e.onshippingcontactselected=t=>Hn(this,void 0,void 0,function*(){return this._handleShippingContactSelected(e,i,t)}),e.onshippingmethodselected=t=>Hn(this,void 0,void 0,function*(){return this._handleShippingMethodSelected(e,i,t)}),e.oncancel=()=>Hn(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 Vn)}}),e.onpaymentauthorized=i=>Hn(this,void 0,void 0,function*(){return this._onPaymentAuthorized(i,e,t)})}_handleShippingContactSelected(e,t,i){var n;return Hn(this,void 0,void 0,function*(){const r=this._transformContactToAddress(i.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===(n=d.consignments[0].selectedShippingOption)||void 0===n?void 0:n.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,i){return Hn(this,void 0,void 0,function*(){const{storeProfile:{storeName:n}}=t,{shippingMethod:{identifier:r}}=i;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:n,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_getUpdatedLineItems(e,t){const i=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>i.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),i.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),i}_updateShippingOption(e){return Hn(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return Hn(this,void 0,void 0,function*(){const i=[`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:i})})}_onPaymentAuthorized(e,t,i){var n;return Hn(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===(n=i.initializationData)||void 0===n?void 0:n.gateway)===jn.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:i.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 Hn(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}function Wn(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}class Yn{create(e){return Wn(window),new ApplePaySession(1,e)}}class Kn{constructor(e){this.scriptLoader=e,this.sdkVersion="1.latest"}loadSdk(){return e=this,t=void 0,n=function*(){(function(e){return"ApplePaySDK"in e})(window)||(yield this.scriptLoader.loadScript(`https://applepay.cdn-apple.com/jsapi/${this.sdkVersion}/apple-pay-sdk.js`),Wn(window))},new((i=void 0)||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())});var e,t,i,n}}const Jn=Rt(e=>{const{getHost:t}=e.getState(),n=new bn(e);return new $n(i({host:t()}),e,new Yn,new Ln(new qn(a(),window,n)),new Kn(new r))},[{id:"applepay"}]);class Zn extends Ji{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 Xn={body:{},headers:{},status:0};class Qn extends Ji{constructor(e,{message:t,errors:i}={}){const{body:n,headers:r,status:o}=e||Xn;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=n,this.headers=r,this.status=o,this.errors=i||[]}}var er,tr,ir,nr,rr,or,ar;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(er||(er={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(tr||(tr={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(ir||(ir={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(nr||(nr={})),function(e){e.pill="pill",e.rect="rect"}(rr||(rr={})),function(e){e.OXXO="oxxo"}(or||(or={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(ar||(ar={}));var sr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class dr{constructor(e,t,i,n){this.formPoster=e,this.paymentIntegrationService=t,this.bigCommercePaymentsRequestSender=i,this.bigCommercePaymentsScriptLoader=n}loadPayPalSdk(e,t,i,n){return sr(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,i,n),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new pn;return this.paypalSdk}createBuyNowCartOrThrow(e){return sr(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new Zn}})}createOrder(e,t){return sr(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:i},t));return n})}createOrderCardFields(e,t){return sr(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n,setupToken:r}=yield this.bigCommercePaymentsRequestSender.createOrder(e,Object.assign({cartId:i},t));return Object.assign({orderId:n},r?{setupToken:r}:{})})}updateOrder(){return sr(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getConsignmentsOrThrow()[0];try{yield this.bigCommercePaymentsRequestSender.updateOrder({availableShippingOptions:i.availableShippingOptions,cartId:t.id,selectedShippingOption:i.selectedShippingOption})}catch(e){throw new Qn}})}getOrderStatus(e,t){return sr(this,void 0,void 0,function*(){try{const{status:i}=yield this.bigCommercePaymentsRequestSender.getOrderStatus(e,t);return i}catch(e){throw new Qn}})}tokenizePayment(e,t){const i=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new Qi(Zi.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},i.source===kt.BuyNow&&{cart_id:i.id}))}submitPayment(e,t,i){return sr(this,void 0,void 0,function*(){const n={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:n},i?{gatewayId:i}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],i=t.availableShippingOptions||[],n=i.find(e=>e.isRecommended),r=(e?i.find(t=>t.id===e):i.find(e=>{var i;return e.id===(null===(i=t.selectedShippingOption)||void 0===i?void 0:i.id)}))||n||i[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,i;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===(i=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===i?void 0:i.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:i}=e,{address:n,name:{full_name:r}}=i[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:n.address_line_1,address2:n.address_line_2,city:n.admin_area_2,countryCode:n.country_code,postalCode:n.postal_code,stateOrProvinceCode:n.admin_area_1})}getValidButtonStyle(e){const{color:t,height:i,label:n,shape:r}=e||{},o={color:t&&nr[t]?t:void 0,height:this.getValidHeight(i),label:n&&ir[n]?n:void 0,shape:r&&rr[r]?r:void 0};return H(o,k)}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 cr="This API endpoint is for internal use only and may change in the future";var lr;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(lr||(lr={}));const ur=lr,hr={"X-Checkout-SDK-Version":"1.864.0"};var pr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class mr{constructor(e){this.requestSender=e}createOrder(e,t){return pr(this,void 0,void 0,function*(){const i=`/api/storefront/payment/${e}`,n=t,r=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.post(i,{headers:r,body:n})).body})}updateOrder(e){return pr(this,void 0,void 0,function*(){const t=e,i=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.put("/api/storefront/initialization/bigcommerce_payments",{headers:i,body:t})).body})}getOrderStatus(e="bigcommerce_payments",t){return pr(this,void 0,void 0,function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body})}}var yr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class gr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,i,n){return yr(this,void 0,void 0,function*(){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,i);return this.loadPayPalSDK(r,n)})}loadPayPalSDK(e,t=!1){return yr(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),i=this.transformConfig(e.attributes),n=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(n,{async:!0,attributes:i})}if(!this.window.paypal)throw new pn;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,i=!0){const{id:n,clientToken:r,initializationData:o}=e;if(!(null==o?void 0:o.clientId))throw new Qi(Zi.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:v}=o,f=h||i,S="bigcommerce_payments_creditcards"===n,w=S?["card"]:[],I=S?[]:["card"],_=p?["credit","paylater"]:[],C=p?[]:["credit","paylater"],b=u?["venmo"]:[],P=u?[]:["venmo"],O=y.filter(e=>!g.includes(e)),E=v?["googlepay"]:[],A=i?["card-fields"]:[],T=this.filterFundingOptions([...I,...C,...P,...O]),k=this.filterFundingOptions([...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:f,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}}}filterFundingOptions(e){const t=["klarna","afterpay"];return e?e.filter(e=>!t.includes(e)):[]}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}const vr=e=>{const{getHost:t}=e.getState();return new dr(Ee(),e,new mr(i({host:t()})),new gr(a()))},fr=40;var Sr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class wr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=V}initialize(e){return Sr(this,void 0,void 0,function*(){const{bigcommerce_payments:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.bigcommerce_payments.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.bigcommerce_payments.onClick" argument is not a function.');this.onError=t.onError||V,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 Sr(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return Sr(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){const{container:i,onClick:n,onComplete: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"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},n&&{onClick:()=>n()}),u={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(t,i)=>this.onHostedCheckoutApprove(t,i,e,r)},h=Object.assign(Object.assign({fundingSource:o.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},c),{height:fr}))},l),s&&u),p=o.Buttons(h);p.isEligible()?p.render(`#${i}`):this.bigCommercePaymentsIntegrationService.removeElement(i)}onHostedCheckoutApprove(e,t,i,n){return Sr(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Sr(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 Sr(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 Ir=Rt(e=>new wr(e,vr(e)),[{id:"bigcommerce_payments"}]);var _r,Cr,br,Pr,Or,Er,Ar,Tr,kr,Dr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Mr{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,i){return Dr(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const n=this.getPayPalFastlaneSdkConfiguration(e,t,i);if(yield this.loadPayPalSdk(n),!this.window.paypalFastlaneSdk)throw new pn}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,i,n){return Dr(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||n){const n=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i);yield this.loadPayPalSdk(n)}if(!this.window.paypalGooglePay)throw new pn;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t){return Dr(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new pn}return this.window.paypalApms})}getPayPalMessages(e,t){return Dr(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new pn;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Dr(this,void 0,void 0,function*(){const i=this.transformConfig(e),n=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(i).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:n})})}getPayPalFastlaneSdkConfiguration(e,t,i){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.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":i.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":n}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i=!0){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||i;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":n,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:n,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=i,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:n},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{clientId:n,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=i;return{options:Object.assign({"client-id":n,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"paypalMessages","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(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}function zr(){return new Mr(o())}!function(e){e.CVV="cvv",e.PAN="pan"}(_r||(_r={}));class Nr{static get(e){const t=`${encodeURIComponent(`${e}`)}=`,i=document.cookie;let n=null;const r=i.indexOf(t);if(r>-1){let e=i.indexOf(";",r);-1===e&&(e=i.length),n=decodeURIComponent(i.substring(r+t.length,e))}return n}static set(e,t,i={secure:!0}){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;const{expires:r,path:o,domain:a,secure:s}=i;if(r)n+=`; expires=${r.toUTCString()}`;else{const e=new Date,t=60;e.setTime(e.getTime()+60*t*1e3),n+=`; expires=${e.toUTCString()}`}o&&(n+=`; path=${o}`),a&&(n+=`; domain=${a}`),s&&(n+="; secure"),document.cookie=n}static remove(e,t){Nr.set(e,"",Object.assign({expires:new Date(0)},t))}}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Cr||(Cr={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(br||(br={})),function(e){e.Always="SCA_ALWAYS"}(Pr||(Pr={})),function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(Or||(Or={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Er||(Er={})),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"}(Tr||(Tr={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(kr||(kr={}));var xr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Fr{constructor(){this.window=window}initializePayPalFastlane(e,t,i){return xr(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:i||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new pn;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return xr(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return xr(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 i={expires:t,secure:!0};Nr.set("bc-fastlane-sessionId",e,i)}removeStorageSessionId(){Nr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Nr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var i,n,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(n=null===(i=null==a?void 0:a.card)||void 0===i?void 0:i.paymentSource)||void 0===n?void 0:n.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||kr.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:i,paymentSource:n}=t,{brand:r,expiry:o,lastDigits:a}=n.card,[s,d]=o.split("-");return[{bigpayToken:i,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:_r.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,i,n){const[r,o]=t.fullName.split(" "),a=(null==i?void 0:i.nationalNumber)||"",s=(null==i?void 0:i.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:n||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return A(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return G(e,["id","phone"])}}function Rr(){return new Fr}function Lr(e){return"string"!=typeof e}function Br(e,t){if(t||e)return function(e){var t,i;const n={},r=H(e.root,Lr),o=H(e.input,Lr),a=H(e.toggle,Lr),s=H(null===(t=e.text)||void 0===t?void 0:t.body,Lr),d=H(null===(i=e.text)||void 0===i?void 0:i.caption,Lr),c=e.branding;return Object.keys(r).length&&(n.root=r),Object.keys(o).length&&(n.input=o),Object.keys(a).length&&(n.toggle=a),Object.keys(s).length&&(n.text={},n.text.body=s),Object.keys(d).length&&(n.text=Object.assign({},n.text),n.text.caption=d),c&&(n.branding=c),n}(function(e,t){var i,n,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,w,I,_,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(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===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var jr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ur{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsSdk=t,this.bigCommercePaymentsFastlaneUtils=i}initialize(e){var t;return jr(this,void 0,void 0,function*(){const{methodId:i,bigcommerce_payments_fastlane:n}=e;if(!i)throw new gn('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(i);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(i),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(i,n))}catch(e){}return Promise.resolve()})}deinitialize(){return jr(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return jr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return jr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return jr(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:i,methodId:n}=e||{};if(!n)throw new gn('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof i)throw new gn('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(n)}catch(e){}}i()})}runPayPalAuthenticationFlowOrThrow(e){return jr(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow().id,n=t.getCustomer(),r=t.getBillingAddress(),o=(null==n?void 0:n.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.bigCommercePaymentsFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.bigCommercePaymentsFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===kr.CANCELED;yield this.updateCustomerDataState(e,s),d?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(i)})}updateCustomerDataState(e,t){var i;return jr(this,void 0,void 0,function*(){const n=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&&n.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),n=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=n.initializationData||{},o=t.getConsignments()||[],a=(null===(i=o[0])||void 0===i?void 0:i.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 i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:n,isFastlaneStylingEnabled:r}=i.initializationData||{};return Br(r?n:{},null==t?void 0:t.styles)}}const qr=Rt(e=>new Ur(e,zr(),Rr()),[{id:"bigcommerce_payments_fastlane"},{id:"bigcommerce_payments_creditcards"}]);var Vr=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Gr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.onError=V}initialize(e){return Vr(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater.onClick" argument is not a function.');this.onError=t.onError||V,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 Vr(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Vr(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:i,onComplete:n,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,i)=>this.onHostedCheckoutApprove(t,i,e,n)},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:fr}))},l),s&&u),n=o.Buttons(t);n.isEligible()&&(n.render(`#${i}`),p=!0)}}),p||this.bigCommercePaymentsIntegrationService.removeElement(i)}onHostedCheckoutApprove(e,t,i,n){return Vr(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Vr(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 Vr(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 Hr=Rt(e=>new Gr(e,vr(e)),[{id:"bigcommerce_payments_paylater"}]);var $r=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Wr{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return $r(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 $r(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return $r(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:i,onClick:n}=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:fr})),createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:t})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(e,t)},n&&{onClick:()=>n()}),c=r.Buttons(d);c.isEligible()?c.render(`#${i}`):this.bigCommercePaymentsIntegrationService.removeElement(i)}}const Yr=Rt(e=>new Wr(e,vr(e)),[{id:"bigcommerce_payments_venmo"}]);class Kr extends Ji{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 Jr extends Qn{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 Zr,Xr,Qr,eo=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class to{constructor(e,t){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=window}initialize(e){var t;return eo(this,void 0,void 0,function*(){const{methodId:i,bolt:n}=e,{onInit:r}=n||{};if(!i)throw new gn('Unable to proceed because "methodId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i);if(!(null===(t=o.initializationData)||void 0===t?void 0:t.publishableKey))throw new Qi(Zi.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 eo(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return eo(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signOutCustomer(e),Promise.resolve()})}executePaymentMethodCheckout(e){return eo(this,void 0,void 0,function*(){const{continueWithCheckoutCallback:t=pe,checkoutPaymentMethodExecuted:i,methodId:n}=e||{},r=this.getCustomerEmail();if(!n)throw new gn('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof t)throw new gn('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');if(r)return this.openBoltCheckoutModalOrThrow(r,n,t,i);t()})}openBoltCheckoutModalOrThrow(e,t,i,n){var r;return eo(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:()=>{i()}};yield o.openCheckout(e,t)}else i();"function"==typeof n&&n({hasBoltAccount:t})}else i()}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 Kr(e.message);throw e}})}getBoltClientOrThrow(){const e=this.boltHostWindow.BoltCheckout;if(!e)throw new nn(Xi.PaymentNotInitialized);return e}hasBoltAccount(e){return eo(this,void 0,void 0,function*(){const t=this.getBoltClientOrThrow();try{return yield t.hasBoltAccount(e)}catch(e){throw new Jr}})}getCustomerEmail(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),i=e.getBillingAddress();return(null==t?void 0:t.email)||(null==i?void 0:i.email)||""}}!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(Zr||(Zr={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(Xr||(Xr={})),function(e){e.Pill="pill",e.Rect="rect"}(Qr||(Qr={}));var io=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class no{constructor(e,t=window){this.scriptLoader=e,this.boltHostWindow=t}loadBoltClient(e,t,i,n,r){return io(this,void 0,void 0,function*(){if(this.boltHostWindow.BoltCheckout)return this.boltHostWindow.BoltCheckout;if(!e)throw new gn('Unable to initialize payment because "publishableKey" argument is not provided.');if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,i)}/connect-bigcommerce.js`,this.getScriptOptions("bolt-connect",e,n,r)),yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,i)}/track.js`,this.getScriptOptions("bolt-track",e)),!this.boltHostWindow.BoltCheckout)throw new pn;return this.boltHostWindow.BoltCheckout})}loadBoltEmbedded(e,t,i){return io(this,void 0,void 0,function*(){if(yield this.scriptLoader.loadScript(`//${this.getDomainURL(!!t,i)}/embed.js`,{async:!0,attributes:{id:"bolt-embedded"}}),!this.boltHostWindow.Bolt)throw new pn;return this.boltHostWindow.Bolt(e)})}getDomainURL(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case Zr.StagingMode:return"connect-staging.bolt.com";case Zr.DevelopmentMode:return`connect.${t.developerDomain}`}return"connect-sandbox.bolt.com"}getScriptOptions(e,t,i,n){return{async:!0,attributes:Object.assign(Object.assign({id:e,"data-publishable-key":t},i&&{"data-shopping-cart-id":i}),n&&{"data-storefront-api-token":n})}}}const ro=Rt(e=>new to(e,new no(a())),[{id:"bolt"}]);class oo extends gn{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 ao extends Ji{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 so=null;const co=["buttons","messages"];var lo,uo,ho,po,mo,yo;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(lo||(lo={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(uo||(uo={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(ho||(ho={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(po||(po={})),function(e){e.PILL="pill",e.RECT="rect"}(mo||(mo={})),function(e){e.CART="cart",e.HOME="homepage",e.PAYMENT="payment",e.PRODUCT="product"}(yo||(yo={}));var go=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class vo{constructor(e,t,i){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.overlay=i,this.dataCollectors={}}initialize(e,t){this.clientToken=e,this.threeDSecureOptions=t}getBraintreeFastlane(e,t,i){return go(this,void 0,void 0,function*(){if(t&&(window.localStorage.setItem("axoEnv","sandbox"),window.localStorage.setItem("fastlaneEnv","sandbox")),!this.braintreeHostWindow.braintreeFastlane){const t=this.getClientTokenOrThrow(),n=yield this.getClient(),r=yield this.getSessionId(e),o=yield this.braintreeScriptLoader.loadFastlane(),a={root:{backgroundColorPrimary:"transparent"}};this.braintreeHostWindow.braintreeFastlane=yield o.create({authorization:t,client:n,deviceData:r,styles:i||a})}return this.braintreeHostWindow.braintreeFastlane})}getClient(){return go(this,void 0,void 0,function*(){if(!this.client){const e=this.getClientTokenOrThrow(),t=yield this.braintreeScriptLoader.loadClient();this.client=t.create({authorization:e})}return this.client})}getPaypal(){return this.braintreePaypal||(this.braintreePaypal=Promise.all([this.getClient(),this.braintreeScriptLoader.loadPaypal()]).then(([e,t])=>t.create({client:e}))),this.braintreePaypal}paypal(e){var{shouldSaveInstrument:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["shouldSaveInstrument"]);const n=Ae();return this.getPaypal().then(e=>{var r;return n&&(null===(r=this.overlay)||void 0===r||r.show({onClick:()=>e.focusWindow()})),e.tokenize(Object.assign({enableShippingAddress:!0,flow:t?"vault":"checkout",useraction:"commit"},i))}).then(e=>{var t;return null===(t=this.overlay)||void 0===t||t.remove(),e}).catch(e=>{var t;throw null===(t=this.overlay)||void 0===t||t.remove(),e})}getPaypalCheckout(e,t,i){return go(this,void 0,void 0,function*(){const n=yield this.getClient(),r=yield this.braintreeScriptLoader.loadPaypalCheckout(),o={client:n};return this.paypalCheckout=yield r.create(o,(n,r)=>{var o;if(n)return i(n);const a=Object.assign(Object.assign({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:co.toString(),intent:e.intent,commit:null===(o=e.commit)||void 0===o||o});this.braintreeHostWindow.paypal?t(r):function(e,t){return so||(so=new Promise((i,n)=>{e.loadPayPalSDK(t,t=>{t?(so=null,n(t)):i(e)})})),so}(r,a).then(()=>t(r))}),this.paypalCheckout})}getDataCollector(e){return go(this,void 0,void 0,function*(){const t=(null==e?void 0:e.paypal)?"paypal":"default";let i=this.dataCollectors[t];if(!i){try{const t=yield this.getClient(),n=yield this.braintreeScriptLoader.loadDataCollector(),r=Object.assign({client:t,kount:!0},e);i=yield n.create(r)}catch(e){if(!zn(e)||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==e.code)throw e;i={deviceData:void 0,teardown:()=>Promise.resolve()}}this.dataCollectors[t]=i}return i})}getBraintreeEnv(e=!1){return e?Nn.Sandbox:Nn.Production}mapToBraintreeShippingAddressOverride(e){return{recipientName:`${e.firstName} ${e.lastName}`,line1:e.address1,line2:e.address2,city:e.city,state:e.stateOrProvinceCode,postalCode:e.postalCode,countryCode:e.countryCode,phone:e.phone}}mapToLegacyShippingAddress(e){const{email:t,phone:i,shippingAddress:n}=e,r=(null==n?void 0:n.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:i,address_line_1:null==n?void 0:n.line1,address_line_2:null==n?void 0:n.line2,city:null==n?void 0:n.city,state:null==n?void 0:n.state,country_code:null==n?void 0:n.countryCode,postal_code:null==n?void 0:n.postalCode}}mapToLegacyBillingAddress(e){const{billingAddress:t,email:i,firstName:n,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:i,first_name:n,last_name:r,phone_number:o,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}getSessionId(e){return go(this,void 0,void 0,function*(){const{deviceData:t}=yield this.getDataCollector({riskCorrelationId:e});return t})}teardown(){return go(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 go(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 go(this,void 0,void 0,function*(){if(!this.venmoCheckout){const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadVenmoCheckout(),n=Object.assign({client:t,allowDesktop:!0,paymentMethodUsage:"multi_use"},e||{});this.venmoCheckout=yield new Promise((e,t)=>{i.create(n,(i,n)=>i?t(i):n.isBrowserSupported()?void e(n):t(new Pn))})}return this.venmoCheckout})}verifyCard(e,t,i){return go(this,void 0,void 0,function*(){const n=yield this.tokenizeCard(e,t);return this.challenge3DSVerification(n,i)})}tokenizeCard(e,t){return go(this,void 0,void 0,function*(){const{paymentData:i}=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}(i))throw new oo(["payment.paymentData"]);const n=this.getErrorsRequiredFields(i);if(!E(n))throw new ao(n);const r=this.mapToCreditCard(i,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 go(this,void 0,void 0,function*(){const i=yield this.get3DS();return this.present3DSChallenge(i,t,e)})}teardownModule(e){return e?e.teardown():Promise.resolve()}getClientTokenOrThrow(){if(!this.clientToken)throw new nn(Xi.PaymentNotInitialized);return this.clientToken}getErrorsRequiredFields(e){const{ccNumber:t,ccExpiry:i}=e,n={};return t||(n.ccNumber=[{message:"Credit card number is required",type:"required"}]),i||(n.ccExpiry=[{message:"Expiration date is required",type:"required"}]),n}mapToCreditCard(e,t){return{data:{creditCard:{cardholderName:e.ccName,number:e.ccNumber,cvv:e.ccCvv,expirationDate:`${e.ccExpiry.month}/${e.ccExpiry.year}`,options:{validate:!1},billingAddress:t&&{countryCodeAlpha2:t.countryCode,locality:t.city,countryName:t.country,postalCode:t.postalCode,streetAddress:t.address2?`${t.address1} ${t.address2}`:t.address1}}},endpoint:"payment_methods/credit_cards",method:"post"}}present3DSChallenge(e,t,i){const{nonce:n,bin:r}=i;if(!this.threeDSecureOptions||!n)throw new nn(Xi.PaymentNotInitialized);const{addFrame:o,removeFrame:a,challengeRequested:s=!0,additionalInformation:d}=this.threeDSecureOptions,c=()=>go(this,void 0,void 0,function*(){const t=yield e.cancelVerifyCard();return u.cancel(new Vn),t}),l=t.toFixed(2),u=new Pi(e.verifyCard({addFrame:(e,t)=>{o&&o(e,t,c)},amount:Number(l),bin:r,challengeRequested:s,nonce:n,removeFrame:a,onLookupComplete:(e,t)=>{t()},collectDeviceData:!0,additionalInformation:d}));return u.promise}}var fo=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class So{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return fo(this,void 0,void 0,function*(){const{braintreepaypal:t,methodId:i}=e,{container:n,onError:r}=t||{};if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(i),!o.clientToken)throw new Qi(Zi.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(i),o=a.getPaymentMethodOrThrow(i)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new Qi(Zi.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,i,Boolean(d.testMode),u)},e=>this.handleError(e,n,r))})}deinitialize(){return fo(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}signIn(e,t){return fo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return fo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()}renderPayPalButton(e,t,i,n,r){const{container:o,onClick:a=V}=t,{paypal:s}=this.braintreeHostWindow,d=null==s?void 0:s.FUNDING.PAYPAL;if(s&&d){const c=s.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(n),fundingSource:d,style:Object.assign(Object.assign({},r),{height:fr}),createOrder:()=>this.setupPayment(e,t,i),onApprove:n=>this.tokenizePayment(n,e,i,t),onClick:a});c.isEligible()&&c.render(`#${o}`)}else this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,i){var n;return fo(this,void 0,void 0,function*(){try{yield this.paymentIntegrationService.loadDefaultCheckout();const t=this.paymentIntegrationService.getState(),r=t.getCheckoutOrThrow().outstandingBalance,o=t.getCartOrThrow().currency.code,a=t.getCustomer(),s=t.getPaymentMethodOrThrow(i),d=null==a?void 0:a.addresses[0],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===(n=s.initializationData)||void 0===n?void 0:n.intent})}catch(e){const{container:i,onError:n}=t;this.handleError(e,i,n)}})}tokenizePayment(e,t,i,n){return fo(this,void 0,void 0,function*(){try{const{deviceData:n}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:i,action:"set_external_checkout",nonce:a,device_data:n,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:i}=n;this.handleError(e,t,i)}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!zn(e))throw e;i(e)}}const wo=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t);return new So(e,Ee(),n,t)},[{id:"braintreepaypal"}]);var Io=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class _o{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return Io(this,void 0,void 0,function*(){const{braintreepaypalcredit:t,methodId:i}=e,{container:n,onError:r}=t||{};if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.braintreepaypalcredit.container" argument is not provided.');let o,a=this.paymentIntegrationService.getState();try{if(o=a.getPaymentMethodOrThrow(i),!o.clientToken)throw new Qi(Zi.MissingPaymentToken)}catch(e){a=yield this.paymentIntegrationService.loadPaymentMethod(i),o=a.getPaymentMethodOrThrow(i)}const{clientToken:s,config:d,initializationData:c}=o,{paymentButtonStyles:l}=c||{},{checkoutTopButtonStyles:u}=l||{};if(!s||!c)throw new Qi(Zi.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,i,Boolean(d.testMode),Object.assign(Object.assign({},u),{height:fr}))},e=>this.handleError(e,n,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,i,n,r){const{container:o,onClick:a=V}=t,{paypal:s}=this.braintreeHostWindow;let d=!1;s&&[s.FUNDING.PAYLATER,s.FUNDING.CREDIT].forEach(c=>{if(!d){const l=s.Buttons({env:n?"sandbox":"production",fundingSource:c,style:r,createOrder:()=>this.setupPayment(e,t,i),onApprove:n=>this.tokenizePayment(n,e,i,t),onClick:a});l.isEligible()&&(l.render(`#${o}`),d=!0)}}),s&&d||this.braintreeIntegrationService.removeElement(o)}setupPayment(e,t,i){var n;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(i),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===(n=s.initializationData)||void 0===n?void 0:n.intent})}catch(e){const{container:i,onError:n}=t;this.handleError(e,i,n)}})}tokenizePayment(e,t,i,n){return Io(this,void 0,void 0,function*(){try{const{deviceData:n}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),r=yield t.tokenizePayment(e),{details:o,nonce:a}=r,s=this.braintreeIntegrationService.mapToLegacyBillingAddress(o),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(o);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:i,action:"set_external_checkout",nonce:a,device_data:n,billing_address:JSON.stringify(s),shipping_address:JSON.stringify(d)}),r}catch(e){const{container:t,onError:i}=n;this.handleError(e,t,i)}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!zn(e))throw e;i(e)}}const Co=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t);return new _o(e,Ee(),n,t)},[{id:"braintreepaypalcredit"}]);function bo(e){return"string"!=typeof e}function Po(e,t){if(t||e)return function(e){var t,i;const n={},r=H(e.root,bo),o=H(e.input,bo),a=H(e.toggle,bo),s=H(null===(t=e.text)||void 0===t?void 0:t.body,bo),d=H(null===(i=e.text)||void 0===i?void 0:i.caption,bo),c=e.branding;return Object.keys(r).length&&(n.root=r),Object.keys(o).length&&(n.input=o),Object.keys(a).length&&(n.toggle=a),Object.keys(s).length&&(n.text={},n.text.body=s),Object.keys(d).length&&(n.text=Object.assign({},n.text),n.text.caption=d),c&&(n.branding=c),n}(function(e,t){var i,n,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,w,I,_,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(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===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var Oo=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Eo{constructor(e,t){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.isAcceleratedCheckoutEnabled=!1}initialize({methodId:e,braintreefastlane:t}){var i;return Oo(this,void 0,void 0,function*(){if(!e)throw new gn('Unable to proceed because "methodId" argument is not provided.');const n=yield this.getValidPaymentMethodOrThrow(e),{isAcceleratedCheckoutEnabled:r,isFastlaneStylingEnabled:o}=n.initializationData||{},a=o?null===(i=n.initializationData)||void 0===i?void 0:i.fastlaneStyles:void 0;this.isAcceleratedCheckoutEnabled=!!r;try{if(this.isAcceleratedCheckoutEnabled){const e=Po(a,null==t?void 0:t.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(n.id,e)}}catch(e){}return Promise.resolve()})}deinitialize(){return Oo(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return Oo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Oo(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return Oo(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:i}=e||{};if("function"!=typeof i)throw new gn('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');const n=this.paymentIntegrationService.getState().getCustomerOrThrow();if(this.isAcceleratedCheckoutEnabled&&n.isGuest){const e=yield this.shouldRunAuthenticationFlow();t&&"function"==typeof t&&t(),e&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(void 0,!0))}i()})}shouldRunAuthenticationFlow(){var e;return Oo(this,void 0,void 0,function*(){const t="braintreeacceleratedcheckout";try{yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t);return(null===(e=i.initializationData)||void 0===e?void 0:e.shouldRunAcceleratedCheckout)||!1}catch(e){return!1}})}getValidPaymentMethodOrThrow(e){return Oo(this,void 0,void 0,function*(){let t=e;try{yield this.paymentIntegrationService.loadPaymentMethod(t)}catch(i){t="braintree"===e?"braintreeacceleratedcheckout":"braintree",yield this.paymentIntegrationService.loadPaymentMethod(t)}return this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t)})}}var Ao=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class To{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}getDeviceSessionId(){return Ao(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 Ao(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getCart(),{clientToken:r,config:o}=i.getPaymentMethodOrThrow(e);if(!r)throw new Qi(Zi.MissingPaymentMethod);this.methodId=e,this.braintreeIntegrationService.initialize(r),this.braintreeFastlane=yield this.braintreeIntegrationService.getBraintreeFastlane(null==n?void 0:n.id,o.testMode,t)})}getBraintreeFastlaneOrThrow(){if(!this.braintreeFastlane)throw new pn;return this.braintreeFastlane}getBraintreeFastlaneComponentOrThrow(){return this.getBraintreeFastlaneOrThrow().FastlaneCardComponent}runPayPalAuthenticationFlowOrThrow(e,t){var i;return Ao(this,void 0,void 0,function*(){try{const n=this.getMethodIdOrThrow(),r=this.getBraintreeFastlaneOrThrow(),{lookupCustomerByEmail:o,triggerAuthenticationFlow:a}=r.identity,s=this.paymentIntegrationService.getState(),d=s.getCartOrThrow(),c=s.getCustomer(),l=s.getBillingAddress(),{isFastlaneShippingOptionAutoSelectEnabled:u}=s.getPaymentMethodOrThrow(n).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:Tn.UNRECOGNIZED,addresses:[],instruments:[]}),void this.saveSessionIdToCookies(d.id);const{authenticationState:m,profileData:y}=yield a(p),g=(null===(i=null==y?void 0:y.shippingAddress)||void 0===i?void 0:i.phoneNumber)||"";if(m===Tn.CANCELED)return yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:[],instruments:[]}),void this.removeSessionIdFromCookies();const v=this.mapPayPalToBcAddress([y.shippingAddress],[g])||[],f=this.getPayPalBillingAddresses(y),S=f?this.mapPayPalToBcAddress([f],[g]):[],w=y.card?this.mapPayPalToBcInstrument(n,[y.card]):[],I=this.mergeShippingAndBillingAddresses(v,S);if(this.saveSessionIdToCookies(d.id),yield this.paymentIntegrationService.updatePaymentProviderCustomer({authenticationState:m,addresses:I,instruments:w}),S.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateBillingAddress(S[0])),S.length>0&&d.lineItems.digitalItems.length>0&&0===d.lineItems.physicalItems.length){const{firstName:e,lastName:t}=I[0],i=Object.assign(Object.assign({},S[0]),{firstName:e,lastName:t});yield this.paymentIntegrationService.updateBillingAddress(i)}v.length>0&&d.lineItems.physicalItems.length>0&&(yield this.paymentIntegrationService.updateShippingAddress(v[0]),t&&u&&(yield this.setShippingOption()))}catch(e){}})}getSessionIdFromCookies(){return Nr.get("bc-fastlane-sessionId")||""}saveSessionIdToCookies(e){const t=new Date;t.setDate(t.getDate()+14),Nr.set("bc-fastlane-sessionId",e,{expires:t,secure:!0})}removeSessionIdFromCookies(){Nr.remove("bc-fastlane-sessionId")}mapPayPalToBcInstrument(e,t){if(t)return t.map(t=>{const{id:i,paymentSource:n}=t,{brand:r,expiry:o,lastDigits:a,binDetails:s}=n.card,[d,c]=o.split("-");return{bigpayToken:i,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:_r.PAN}})}mapPayPalToBcAddress(e,t){if(!e)return[];const i=this.paymentIntegrationService.getState().getCountries()||[],n=e=>{const t=i.find(t=>t.code===e);return(null==t?void 0:t.name)||""};return e.map(e=>({id:Date.now(),type:"paypal-address",firstName:e.firstName||"",lastName:e.lastName||"",company:e.company||"",address1:e.streetAddress,address2:e.extendedAddress||"",city:e.locality,stateOrProvince:e.region,stateOrProvinceCode:e.region,country:n(e.countryCodeAlpha2),countryCode:e.countryCodeAlpha2,postalCode:e.postalCode,phone:t&&t[0]||"",customFields:[]}))}getPayPalBillingAddresses(e){const{card:t,name:i}=e||{};if(!t)return;const{firstName:n,lastName:r}=t.paymentSource.card.billingAddress,{firstName:o,lastName:a}=i||{},{shippingAddress:s}=e||{},d=Object.assign(Object.assign({},t.paymentSource.card.billingAddress),{firstName:n||o,lastName:r||a});return s&&A(this.normalizeAddress(d),this.normalizeAddress(s))?s:d}normalizeAddress(e){return G(e,["id"])}mergeShippingAndBillingAddresses(e,t){const i=t.filter(t=>!e.some(e=>A(this.normalizeAddress(e),this.normalizeAddress(t))));return[...e,...i]}getMethodIdOrThrow(){if(!this.methodId)throw new gn('Unable to proceed because "methodId" argument is not provided.');return this.methodId}setShippingOption(){var e;return Ao(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getConsignments()||[],i=(null===(e=t[0])||void 0===e?void 0:e.availableShippingOptions)||[],n=i.find(e=>e.isRecommended);if(n||i.length){const e=n||i[0];yield this.paymentIntegrationService.selectShippingOption(e.id)}})}}const ko=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t),r=new To(e,n);return new Eo(e,r)},[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);var Do=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Mo{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i,this.buttonClassName="visa-checkout-wrapper",this.onError=V}initialize(e){return Do(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:i}=e;if(!i)throw new gn('Unable to proceed because "methodId" argument is not provided.');if(!t)throw new gn('Unable to proceed because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState(),r=n.getCheckoutOrThrow(),{clientToken:o,config:a}=n.getPaymentMethodOrThrow(i),s=n.getStoreConfigOrThrow();if(!o)throw new Qi(Zi.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||V;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 Do(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}signIn(){throw new vn('In order to sign in via VisaCheckout, the shopper must click on "Visa Checkout" button.')}signOut(e){return Do(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 Do(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(n),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e,t){const i=document.querySelector(`#${e}`);if(!i)throw new Error("Unable to proceed because the provided container ID is not valid.");return this.insertVisaCheckoutButton(i,t)}insertVisaCheckoutButton(e,t){const i=document.createElement("div");return i.style.display="flex",i.style.flexDirection="column",i.style.visibility="hidden",i.style.width="max-content",i.className=t,i.innerHTML='\n <img\n alt="Visa Checkout"\n class="v-button"\n role="button"\n src="https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178"\n />\n <a class="v-learn v-learn-default" style="text-align: right; display: block; font-size: 10px; color: #003366;" href="#" data-locale="en_US">Tell Me More</a>',e.appendChild(i),i}handleError(e){if("function"!=typeof this.onError)throw e;this.onError(e)}}const zo=Rt(e=>{const t=window,i=new bn(e),n=new Ln(new qn(a(),t,i));return new Mo(e,Ee(),n)},[{id:"braintreevisacheckout"}]);class No{constructor(e){if(!e)throw new Error("Currency settings missing");const{decimalPlaces:t,symbolLocation:i,symbol:n,thousandsSeparator:r,decimalSeparator:o}=e;if("string"!=typeof i||"string"!=typeof n||"string"!=typeof r||"string"!=typeof o||"string"!=typeof t)throw new gn("Invalid currency settings provided");this._decimalPlaces=parseInt(t,10),this._symbolLocation=i,this._symbol=n,this._thousandsSeparator=r,this._decimalSeparator=o}format(e){if("number"!=typeof e)throw new gn("Invalid amount provided");const t=this._formatNumber(e),i=this._formatCurrency(t);return e<0?`-${i}`:i}_formatNumber(e){const t=Math.abs(e),[i,n=""]=this._toFixed(t,this._decimalPlaces).split("."),r=i.replace(/\B(?=(\d{3})+(?!\d))/g,this._thousandsSeparator);return this._decimalPlaces<1?r:[r,n].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 xo=class{constructor(e){this._storeConfig=e,this._customerFormatter=new No(this._storeConfig.shopperCurrency),this._storeFormatter=new No(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};xo=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],xo);const Fo=xo,Ro=(e,t)=>!!e&&(!!e.lineItems.physicalItems.some(e=>e.isShippingRequired)||!(!t||!e.lineItems.customItems)&&e.lineItems.customItems.length>0);var Lo,Bo,jo,Uo,qo,Vo,Go,Ho,$o;function Wo(e){return e in Vo}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Lo||(Lo={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Bo||(Bo={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(jo||(jo={})),function(e){e.pill="pill",e.rect="rect"}(Uo||(Uo={})),function(e){e.ESTIMATED="ESTIMATED",e.FINAL="FINAL",e.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(qo||(qo={})),function(e){e.AMEX="AMEX",e.DISCOVER="DISCOVER",e.INTERAC="INTERAC",e.JCB="JCB",e.MC="MASTERCARD",e.VISA="VISA"}(Vo||(Vo={})),function(e){e.OFFER="OFFER",e.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.SHIPPING_OPTION="SHIPPING_OPTION"}(Go||(Go={})),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"}(Ho||(Ho={})),function(e){e.INITIALIZE="INITIALIZE",e.SHIPPING_OPTION="SHIPPING_OPTION",e.SHIPPING_ADDRESS="SHIPPING_ADDRESS",e.OFFER="OFFER"}($o||($o={}));var Yo,Ko=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Jo{constructor(e,t){this._gatewayIdentifier=e,this._paymentIntegrationService=t,this._isBuyNowFlow=!1,this._shouldRequestShipping=!0}mapToShippingAddressRequestBody({shippingAddress:e}){if(!e)return;const{company:t="",phone:i=""}=this._paymentIntegrationService.getState().getShippingAddress()||{};return this._mapToAddressRequestBody(e,t,i)}mapToBillingAddressRequestBody(e){const{billingAddress:t}=e.paymentMethodData.info;if(!t)return;const{company:i="",phone:n="",email:r,customFields:o=[]}=this._paymentIntegrationService.getState().getBillingAddress()||{};return Object.assign(Object.assign({},this._mapToAddressRequestBody(t,i,n,o)),{email:r||e.email})}mapToExternalCheckoutData(e){var t;const{paymentMethodData:{tokenizationData:{token:i},info:{cardNetwork:n,cardDetails:r}}}=e;if(!i)throw new Qi(Zi.MissingPaymentToken);return Promise.resolve(Object.assign({nonce:i,card_information:{type:n,number:r}},this._isBuyNowFlow&&{cart_id:null===(t=this._paymentIntegrationService.getState().getCart())||void 0===t?void 0:t.id}))}getRequiredData(){var e;return Ko(this,void 0,void 0,function*(){const t={emailRequired:!0};if(!this._isShippingAddressRequired())return t;const i=yield this._paymentIntegrationService.loadShippingCountries(),n=null===(e=i.getShippingCountries())||void 0===e?void 0:e.map(e=>e.code);return Object.assign(Object.assign({},t),{shippingAddressRequired:!0,shippingAddressParameters:Object.assign({phoneNumberRequired:!0},n&&{allowedCountryCodes:n}),shippingOptionRequired:!0})})}getCallbackIntents(){return this._isShippingAddressRequired()?[Go.OFFER,Go.SHIPPING_ADDRESS,Go.SHIPPING_OPTION]:[Go.OFFER]}getCallbackTriggers(){return{availableTriggers:[$o.INITIALIZE,$o.SHIPPING_ADDRESS,$o.SHIPPING_OPTION,$o.OFFER],initializationTrigger:[$o.INITIALIZE],addressChangeTriggers:[$o.INITIALIZE,$o.SHIPPING_ADDRESS],shippingOptionsChangeTriggers:[$o.SHIPPING_OPTION],offerChangeTriggers:[$o.OFFER]}}getNonce(e){var t;const i=null===(t=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.nonce;if(!i)throw new Qi(Zi.MissingPaymentToken);return Promise.resolve(i)}extraPaymentData(){return Promise.resolve(void 0)}getMerchantInfo(){const{googleMerchantName:e,googleMerchantId:t,platformToken:i}=this.getGooglePayInitializationData();return{merchantName:e,merchantId:t,authJwt:i}}getTransactionInfo(){let e;if(this._isBuyNowFlow)e=this._getCurrencyCodeOrThrow();else{const{getCartOrThrow:t}=this._paymentIntegrationService.getState();e=t().currency.code}const t=this.getGooglePayInitializationData().storeCountry;return Object.assign(Object.assign({},t&&{countryCode:t}),{currencyCode:e,totalPriceStatus:qo.ESTIMATED,totalPrice:"0"})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData().gatewayMerchantId;if(!e)throw new gn("Unable to proceed, gatewayMerchantId is missing.");return{gateway:this._gatewayIdentifier,gatewayMerchantId:e}}getCardParameters(){return{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.getPaymentMethod().supportedCards.filter(Wo).map(e=>Vo[e]),billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!0}}}initialize(e,t,i){return this._getPaymentMethodFn=e,this._isBuyNowFlow=Boolean(t),this._currencyCode=i,this._isBuyNowFlow&&this._getCurrencyCodeOrThrow(),Promise.resolve()}handleShippingAddressChange(e){var t,i,n,r;return Ko(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 Fo(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===(i=d.selectedShippingOption)||void 0===i?void 0:i.id)||(null==u?void 0:u.id)||(null===(n=l[0])||void 0===n?void 0:n.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 Ko(this,void 0,void 0,function*(){if("shipping_option_unselected"!==e)return this._paymentIntegrationService.selectShippingOption(e)})}getTotalPrice(){const{getCheckoutOrThrow:e,getCartOrThrow:t}=this._paymentIntegrationService.getState(),{decimalPlaces:i}=t().currency;return J(e().outstandingBalance,i).toFixed(i)}handleCoupons(e){return Ko(this,void 0,void 0,function*(){const{redemptionCodes:t=[]}=e,{offers:i}=this.getAppliedCoupons();let n;return yield t.reduce((e,t)=>Ko(this,void 0,void 0,function*(){if(yield e,i.some(({redemptionCode:e})=>e===t))return;const r=yield this.applyCoupon(t);r&&(n=r)}),Promise.resolve()),yield i.reduce((e,i)=>Ko(this,void 0,void 0,function*(){yield e,t.includes(i.redemptionCode)||(yield this._paymentIntegrationService.removeCoupon(i.redemptionCode))}),Promise.resolve()),{newOfferInfo:this.getAppliedCoupons(),error:n}})}getAppliedCoupons(){const e=this._paymentIntegrationService.getState(),{coupons:t}=e.getCheckout()||{};return{offers:(t||[]).map(e=>{const{displayName:t,code:i}=e;return{redemptionCode:i,description:t}})}}applyCoupon(e){return Ko(this,void 0,void 0,function*(){let t;try{yield this._paymentIntegrationService.applyCoupon(e)}catch(e){return e instanceof Error&&(t={reason:Ho.OFFER_INVALID,message:e.message,intent:$o.OFFER}),t}})}setShouldRequestShipping(e){this._shouldRequestShipping=e}getGooglePayInitializationData(){return tn(this.getPaymentMethod().initializationData,()=>new gn("Missing initialization data."))}getPaymentMethod(){return tn(this._getPaymentMethodFn,()=>new nn(Xi.PaymentNotInitialized))()}getGatewayIdentifier(){return this._gatewayIdentifier}setGatewayIdentifier(e){this._gatewayIdentifier=e||this.getGatewayIdentifier()}_isShippingAddressRequired(){const{getCartOrThrow:e,getStoreConfigOrThrow:t,getShippingAddress:i}=this._paymentIntegrationService.getState(),n=t();let r;return r=Wt(n.checkoutSettings.features,"PI-4290.google_pay_require_shipping_address")?this._shouldRequestShipping:void 0===i(),r&&Ro(e(),n)}_mapToAddressRequestBody(e,t,i,n){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||i,customFields:n||[]}}_getFirstAndLastName(e){const t=e.split(" ");return 1===t.length?[e,""]:[t.slice(0,-1).join(" "),t[t.length-1]]}_getCurrencyCodeOrThrow(){return tn(this._currencyCode,()=>new gn('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}_getGooglePayShippingOption({id:e,cost:t,description:i,additionalDescription:n}){var r;const o=null===(r=this._currencyService)||void 0===r?void 0:r.toCustomerCurrency(t);return this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features["PI-3540.googlepay_new_shipping_options_description"]?{id:e,label:`${o||t} ${i}`,description:n}:{id:e,label:i,description:o||t}}}function Zo(e){return"object"==typeof e&&null!==e&&"statusCode"in e}function Xo(e){return Object.values(Yo).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"}(Yo||(Yo={}));var Qo=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ea{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t;return Qo(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!Xo(e.methodId))throw new gn('Unable to proceed because "methodId" is not a valid key.');this._methodId=e.methodId;const i=e[this._getMethodId()];if(!i)throw new gn("Unable to proceed without valid options.");let n,r=this._paymentIntegrationService.getState();try{n=r.getPaymentMethodOrThrow(this._getMethodId())}catch(e){r=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId()),n=r.getPaymentMethodOrThrow(this._getMethodId())}try{yield this._googlePayPaymentProcessor.initialize(()=>n,this._getGooglePayClientOptions(null===(t=n.initializationData)||void 0===t?void 0:t.storeCountry))}catch(e){return}this._addPaymentButton(i)})}signIn(){return Promise.reject(new vn('In order to sign in via Google Pay, the shopper must click on "Google Pay" button.'))}signOut(){var e;return Qo(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{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,shippingAddress:i,shippingOptionData:n,offerData:r})=>Qo(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(i):void 0;s.includes(t)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(n.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:qo.FINAL,totalPrice:p})},c&&{newShippingOptionParameters:c}),l&&{newOfferInfo:l}),h&&{error:h})})}}}_addPaymentButton({container:e,buttonColor:t,buttonType:i,onClick:n,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!=i?i:"plain",onClick:this._handleClick(r,n)})}_handleClick(e,t){return i=>Qo(this,void 0,void 0,function*(){i.preventDefault(),t&&"function"==typeof t&&t();try{yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let i=t;if(Zo(t)){if("CANCELED"===t.statusCode)throw new Vn;i=new Kr(JSON.stringify(t))}throw null==e||e(new Kr("An error occurred while requesting your Google Pay payment details.")),i}})}_interactWithPaymentSheet(){return Qo(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet(),t=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e),i=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(e),n="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;t&&(yield this._paymentIntegrationService.updateBillingAddress(t)),i&&(yield this._paymentIntegrationService.updateShippingAddress(i)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodId(),e,n)})}_getMethodId(){return tn(this._methodId,()=>new nn(Xi.PaymentNotInitialized))}}var ta=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ia{constructor(e,t,i,n){this._scriptLoader=e,this._gateway=t,this._requestSender=i,this._formPoster=n,this._baseRequest={apiVersion:2,apiVersionMinor:0}}initialize(e,t,i,n){return ta(this,void 0,void 0,function*(){this._paymentsClient=yield this._scriptLoader.getGooglePaymentsClient(e().config.testMode,t),yield this._gateway.initialize(e,i,n),this._buildButtonPayloads()})}initializeWidget(){return ta(this,void 0,void 0,function*(){yield this._buildWidgetPayloads(),yield this._determineReadinessToPay(),this._prefetchGooglePaymentData()})}getNonce(e){return this._gateway.getNonce(e)}extraPaymentData(){return ta(this,void 0,void 0,function*(){return this._gateway.extraPaymentData()})}addPaymentButton(e,t){const i=document.querySelector(`#${e}`);if(!i)return;const n=this._getPaymentsClient().createButton(Object.assign(Object.assign({},t),{allowedPaymentMethods:[this._getBaseCardPaymentMethod()]}));return i.appendChild(n)}showPaymentSheet(){return ta(this,void 0,void 0,function*(){const e=this._getPaymentDataRequest();return this._getPaymentsClient().loadPaymentData(e)})}setExternalCheckoutXhr(e,t){return ta(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t)})}setExternalCheckoutForm(e,t,i){return ta(this,void 0,void 0,function*(){return this._setExternalCheckout(e,t,!0,i)})}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 ta(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 ta(this,void 0,void 0,function*(){return this._gateway.handleShippingAddressChange(e)})}handleShippingOptionChange(e){return ta(this,void 0,void 0,function*(){yield this._gateway.handleShippingOptionChange(e)})}handleCoupons(e){return ta(this,void 0,void 0,function*(){return this._gateway.handleCoupons(e)})}getTotalPrice(){return this._gateway.getTotalPrice()}_setExternalCheckout(e,t,i=!1,n){return ta(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(i)return new Promise(e=>{this._formPoster.postForm(n?`${n}/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"},hr),body:o})})}_prefetchGooglePaymentData(){const e=this._getPaymentDataRequest();e.transactionInfo=this._gateway.getTransactionInfo(),this._getPaymentsClient().prefetchPaymentData(e)}_determineReadinessToPay(){return ta(this,void 0,void 0,function*(){try{const{result:e}=yield this._getPaymentsClient().isReadyToPay(this._getIsReadyToPayRequest());if(!1===e)throw new Kr("Google Pay is not supported by the current device and browser, please try another payment method.")}catch(e){if(e instanceof Kr)throw e;throw new Kr}})}_buildButtonPayloads(){this._baseCardPaymentMethod={type:"CARD",parameters:this._gateway.getCardParameters()}}_buildWidgetPayloads(){return ta(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()}}),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()),{callbackIntents:this._gateway.getCallbackIntents(),offerInfo:this._gateway.getAppliedCoupons()}),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 tn(e,()=>new nn(Xi.PaymentNotInitialized))}}class na{constructor(e){this._scriptLoader=e,this._window=window}getGooglePaymentsClient(e=!1,t){return i=this,n=void 0,o=function*(){if(yield this._scriptLoader.loadScript("https://pay.google.com/gp/p/js/pay.js"),!this._window.google)throw new pn;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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}function ra(){return new na(a())}const oa=Rt(e=>{const t=i();return new ea(e,new ia(ra(),new Jo("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),aa=Rt(e=>{const t=i();return new ea(e,new ia(ra(),new Jo("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]);class sa extends Jo{constructor(e){super("authorizenet",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return i=this,n=void 0,o=function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return function(e){if(!function(e){return"paymentGatewayId"in e}(e))throw new Qi(Zi.MissingPaymentMethod)}(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.paymentGatewayId}}}const da=Rt(e=>new ea(e,new ia(ra(),new sa(e),i(),Ee())),[{id:"googlepayauthorizenet"}]),ca=e=>"object"==typeof e&&null!==e&&"body"in e;function la(e){if(!function(e){return"checkoutcomkey"in e}(e))throw new Qi(Zi.MissingPaymentMethod)}var ua=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ha extends Jo{constructor(e,t){super("checkoutltd",e),this._requestSender=t}processAdditionalAction(e){return new Promise((t,i)=>{if(ca(e)&&function(e){var t;if("object"!=typeof e||null===e)return!1;const i=e;return"string"==typeof(null===(t=i.three_ds_result)||void 0===t?void 0:t.acs_url)&&"string"==typeof i.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);i(e)})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ua(this,void 0,void 0,function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);let n;try{n=JSON.parse(i.nonce)}catch(e){throw new gn("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 Qi(Zi.MissingPaymentToken)}(n),i.nonce=yield this._tokenize(n),i})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();return la(e),{gateway:this.getGatewayIdentifier(),gatewayMerchantId:e.checkoutcomkey}}_tokenize(e){return ua(this,void 0,void 0,function*(){const t=this.getPaymentMethod().config.testMode?"https://api.sandbox.checkout.com/tokens":"https://api.checkout.com/tokens",i=this.getGooglePayInitializationData();la(i);const{body:n}=yield this._requestSender.post(t,{credentials:!1,body:{type:"googlepay",token_data:e},headers:{Authorization:i.checkoutcomkey,"Content-Type":ur.Json,"X-XSRF-TOKEN":null}});return n.token})}}const pa=Rt(e=>{const t=i();return new ea(e,new ia(ra(),new ha(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]);class ma extends Jo{constructor(e){super("cybersource",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return i=this,n=void 0,o=function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}const ya=Rt(e=>new ea(e,new ia(ra(),new ma(e),i(),Ee())),[{id:"googlepaycybersourcev2"}]),ga=Rt(e=>new ea(e,new ia(ra(),new ma(e),i(),Ee())),[{id:"googlepaybnz"}]);class va extends Jo{constructor(e){super("chase",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return i=this,n=void 0,o=function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}const fa=Rt(e=>new ea(e,new ia(ra(),new va(e),i(),Ee())),[{id:"googlepayorbital"}]);var Sa,wa,Ia,_a,Ca,ba,Pa,Oa,Ea,Aa;!function(e){e.SHIPPING="shipping",e.BILLING="billing"}(Sa||(Sa={})),function(e){e.SPLIT="split",e.FULL="full",e.ORGANIZATION="organization"}(wa||(wa={})),function(e){e.SUCCESS="success",e.ERROR="error"}(Ia||(Ia={})),function(e){e.CreditCard="card",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"}(_a||(_a={})),function(e){e.NEVER="never",e.AUTO="auto",e.ALWAYS="always",e.PAYMENT="payment",e.IF_REQUIRED="if_required"}(Ca||(Ca={})),function(e){e.V3="v3",e.ACACIA="acacia",e.BASIL="basil",e.CLOVER="clover"}(ba||(ba={})),function(e){e.PAYMENT="payment",e.AUTHENTICATION="linkAuthentication",e.SHIPPING="address",e.EXPRESS_CHECKOUT="expressCheckout"}(Pa||(Pa={})),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"}(Oa||(Oa={})),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"}(Ea||(Ea={})),function(e){e.ON_SESSION="on_session",e.OFF_SESSION="off_session"}(Aa||(Aa={}));var Ta=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ka{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}getStripeClient(e,t,i,n,r){return Ta(this,void 0,void 0,function*(){if(this.stripeWindow.bcStripeClient)return this.stripeWindow.bcStripeClient;const o=yield this.load(i),{stripePublishableKey:a,stripeConnectedAccount:s}=e,d=o(a,Object.assign(Object.assign(Object.assign(Object.assign({},s?{stripeAccount:s}:{}),t?{locale:t}:{}),n?{betas:n}:{}),r?{apiVersion:r}:{}));return Object.assign(this.stripeWindow,{bcStripeClient:d}),d})}getElements(e,t){return Ta(this,void 0,void 0,function*(){let i=this.stripeWindow.bcStripeElements;return i?yield this.updateStripeElements(t):(i=e.elements(t),Object.assign(this.stripeWindow,{bcStripeElements:i})),i})}updateStripeElements(e){return Ta(this,void 0,void 0,function*(){const t=this.stripeWindow.bcStripeElements;t&&(t.update(e),yield t.fetchUpdates())})}getCheckoutSession(e,t){return Ta(this,void 0,void 0,function*(){let i=this.stripeWindow.bcStripeCheckoutSession;return i||(i=yield e.initCheckout(t),Object.assign(this.stripeWindow,{bcStripeCheckoutSession:i})),i})}load(e){return Ta(this,void 0,void 0,function*(){if(!this.stripeWindow.Stripe&&(yield this.scriptLoader.loadScript(this.getScriptUrl(e)),!this.stripeWindow.Stripe))throw new pn;return this.stripeWindow.Stripe})}getScriptUrl(e){return e&&e!==ba.V3?`https://js.stripe.com/${e}/stripe.js`:"https://js.stripe.com/v3/"}}const Da=["payment_element_beta_2","alipay_pm_beta_1","link_default_integration_beta_1","shipping_address_element_beta_1","address_element_beta_1"],Ma="2020-03-02;alipay_beta=v1;link_beta=v1";function za(e){if(!function(e){return"stripeConnectedAccount"in e&&"stripePublishableKey"in e&&"stripeVersion"in e}(e))throw new Qi(Zi.MissingPaymentMethod)}var Na=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class xa extends Jo{constructor(e,t){super("stripe",e),this.paymentIntegrationService=e,this.scriptLoader=t}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return Na(this,void 0,void 0,function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);let n;try{n=JSON.parse(i.nonce)}catch(e){throw new gn("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 Qi(Zi.MissingPaymentToken)}(n),i.nonce=n.id,i})}getPaymentGatewayParameters(){const e=this.getGooglePayInitializationData();za(e);const{stripeVersion:t,stripePublishableKey:i,stripeConnectedAccount:n}=e;return{gateway:this.getGatewayIdentifier(),"stripe:version":t,"stripe:publishableKey":`${i}/${n}`}}processAdditionalAction(e,t){var i;return Na(this,void 0,void 0,function*(){if(!t)throw new oo(["payment"]);if(!ca(e)||("object"!=typeof(n=e.body)||null===n||!("three_ds_result"in n)||!("errors"in n)))throw e;var n;if(Z(e.body.errors,{code:"three_d_secure_required"})){const n=this.getGooglePayInitializationData();za(n),this.stripeUPEClient=yield this.loadStripeJs(n,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 Vn;throw new Kr}if(!(null==o?void 0:o.paymentIntent)&&!a)throw new Qn;return this.paymentIntegrationService.submitPayment({methodId:t,paymentData:{nonce:(null===(i=null==o?void 0:o.paymentIntent)||void 0===i?void 0:i.id)||r}})}throw e})}loadStripeJs(e,t){return Na(this,void 0,void 0,function*(){if(this.stripeUPEClient)return this.stripeUPEClient;const i=this.paymentIntegrationService.getState().getCartLocale();return"googlepaystripeocs"===t&&e.useNewStripeJsVersion?this.scriptLoader.getStripeClient(e,i,ba.CLOVER):this.scriptLoader.getStripeClient(e,i,ba.V3,Da,Ma)})}_isCancellationError(e){var t,i;return e&&-1!==(null===(i=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===i?void 0:i.indexOf("canceled"))}_throwDisplayableStripeError(e){if(P(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}}const Fa=Rt(e=>new ea(e,new ia(ra(),new xa(e,new ka(a())),i(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeocs"}]),Ra=Rt(e=>new ea(e,new ia(ra(),new xa(e,new ka(a())),i(),Ee())),[{id:"googlepaystripeupe"}]);class La extends Jo{constructor(e){super("worldpay",e)}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return i=this,n=void 0,o=function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}const Ba=Rt(e=>new ea(e,new ia(ra(),new La(e),i(),Ee())),[{id:"googlepayworldpayaccess"}]);var ja=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ua extends Jo{constructor(e,t){super("braintree",e),this._braintreeSdk=t,this._methodId=Yo.BRAINTREE,this._service=e}initialize(e,t,i){const n=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return ja(this,void 0,void 0,function*(){yield n.initialize.call(this,e,t,i);let r=n.getPaymentMethod.call(this);if(r.clientToken||(r=(yield this._service.loadPaymentMethod(this._methodId)).getPaymentMethodOrThrow(this._methodId)),!r.clientToken||!r.initializationData)throw new Qi(Zi.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 i;return ja(this,void 0,void 0,function*(){const n=yield t.getNonce.call(this,e),{clientToken:r,initializationData:o}=t.getPaymentMethod.call(this);if(!r||!o||!(null===(i=o.card_information)||void 0===i?void 0:i.bin))throw new Qi(Zi.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,n,s)).nonce}return n})}extraPaymentData(){return ja(this,void 0,void 0,function*(){return{deviceSessionId:yield this._getBraintreeDeviceData()}})}mapToExternalCheckoutData(e){const t=Object.create(null,{mapToExternalCheckoutData:{get:()=>super.mapToExternalCheckoutData}});return ja(this,void 0,void 0,function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);let n;try{n=JSON.parse(i.nonce)}catch(e){throw new gn("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 Qi(Zi.MissingPaymentToken)}(n),i.nonce=n.androidPayCards[0].nonce,i.card_information.bin=n.androidPayCards[0].details.bin,i.card_information.isNetworkTokenized=n.androidPayCards[0].details.isNetworkTokenized,i})}getCardParameters(){return super.getCardParameters()}getPaymentGatewayParameters(){const e=Object.create(null,{getMerchantInfo:{get:()=>super.getMerchantInfo},getTransactionInfo:{get:()=>super.getTransactionInfo},getRequiredData:{get:()=>super.getRequiredData}});return ja(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 Qi(Zi.MissingPaymentMethod);return this._braintreeGooglePayment}_getBraintreeDeviceData(){return ja(this,void 0,void 0,function*(){const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e})}_braintreePresent3DSChallenge(e,t,i,n){return new Pi(e.verifyCard({amount:t,bin:n,nonce:i,onLookupComplete:(e,t)=>{t()}})).promise}}const qa=Rt(e=>{const t=i(),n=window,r=new bn(e),o=new Ln(new qn(a(),n,r));return new ea(e,new ia(ra(),new Ua(e,o),t,Ee()))},[{id:"googlepaybraintree"}]);var Va=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ga{constructor(e){this.scriptLoader=e,this.window=window}getPayPalFastlaneSdk(e,t,i){return Va(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const n=this.getPayPalFastlaneSdkConfiguration(e,t,i);if(yield this.loadPayPalSdk(n),!this.window.paypalFastlaneSdk)throw new pn}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,i,n){return Va(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||n){const n=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i);yield this.loadPayPalSdk(n)}if(!this.window.paypalGooglePay)throw new pn;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t){return Va(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new pn}return this.window.paypalApms})}getPayPalMessages(e,t){return Va(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new pn;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return Va(this,void 0,void 0,function*(){const i=this.transformConfig(e),n=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(i).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:n})})}getPayPalFastlaneSdkConfiguration(e,t,i){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,attributionId:d}=r;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t,intent:o},attributes:{"data-client-metadata-id":i.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":n}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i=!0){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||i;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":n,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:n,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=i,u=l,h=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:n},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{clientId:n,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=i;return{options:Object.assign({"client-id":n,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":o}}}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}function Ha(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 Qi(Zi.MissingPaymentMethod)}var $a=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Wa extends Jo{constructor(e,t){super("paypalsb",e),this.payPalCommerceSdk=t,this.service=e}initialize(e,t,i){const n=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return $a(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:i;if(!c)throw new Qi(Zi.MissingPaymentMethod);yield n.initialize.call(this,e,t,c);const l=n.getPaymentMethod.call(this);if(!l.initializationData)throw new Qi(Zi.MissingPaymentMethod);Ha(l);const u=yield this.payPalCommerceSdk.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 $a(this,void 0,void 0,function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),i})}}const Ya=Rt(e=>new ea(e,new ia(ra(),new Wa(e,new Ga(a())),i(),Ee())),[{id:"googlepaypaypalcommerce"}]);var Ka=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ja extends Jo{constructor(e,t){super("googlepay_bigcommerce_payments",e),this.payPalSdkHelper=t,this.service=e}initialize(e,t,i){const n=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});var r,o,a,s,d;return Ka(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:i;if(!c)throw new Qi(Zi.MissingPaymentMethod);yield n.initialize.call(this,e,t,c);const l=n.getPaymentMethod.call(this);if(!l.initializationData)throw new Qi(Zi.MissingPaymentMethod);Ha(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 Ka(this,void 0,void 0,function*(){const i=yield t.mapToExternalCheckoutData.call(this,e);return i.nonce=btoa(i.nonce),i})}}const Za=Rt(e=>new ea(e,new ia(ra(),new Ja(e,new Mr(a())),i(),Ee())),[{id:"googlepay_bigcommerce_payments"}]);function Xa(){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 Qa=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class es extends Jo{constructor(e,t){super("worldlinena",e),this.formPoster=t}extraPaymentData(){return Qa(this,void 0,void 0,function*(){return Promise.resolve({browser_info:Xa()})})}processAdditionalAction(e){return Qa(this,void 0,void 0,function*(){if(!function(e){return ca(e)&&(t=e.body,D(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&O(t.errors)&&Z(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:i,payer_auth_request:n,merchant_data:r}=t||{};if(!i||!n||!r)throw new oo(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(i,{threeDSSessionData:n,creq:r},e,"_top")})})}}const ts=Rt(e=>new ea(e,new ia(ra(),new es(e,Ee()),i(),Ee())),[{id:"googlepaytdonlinemart"}]);var is,ns,rs,os,as,ss,ds;!function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(is||(is={})),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"}(os||(os={})),function(e){e.pill="pill",e.rect="rect"}(as||(as={})),(ss||(ss={})).OXXO="oxxo",function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(ds||(ds={}));var cs=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ls{constructor(e,t,i,n){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=i,this.paypalCommerceScriptLoader=n}loadPayPalSdk(e,t,i,n){return cs(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,i,n),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new pn;return this.paypalSdk}createBuyNowCartOrThrow(e){return cs(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new Zn}})}createOrder(e,t){return cs(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:i},t));return n})}createOrderCardFields(e,t){return cs(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n,setupToken:r}=yield this.paypalCommerceRequestSender.createOrder(e,Object.assign({cartId:i},t));return Object.assign({orderId:n},r?{setupToken:r}:{})})}updateOrder(){return cs(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getConsignmentsOrThrow()[0];try{yield this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:i.availableShippingOptions,cartId:t.id,selectedShippingOption:i.selectedShippingOption})}catch(e){throw new Qn}})}getOrderStatus(e,t){return cs(this,void 0,void 0,function*(){try{const{status:i}=yield this.paypalCommerceRequestSender.getOrderStatus(e,t);return i}catch(e){throw new Qn}})}tokenizePayment(e,t){const i=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new Qi(Zi.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},i.source===kt.BuyNow&&{cart_id:i.id}))}submitPayment(e,t,i){return cs(this,void 0,void 0,function*(){const n={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:n},i?{gatewayId:i}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],i=t.availableShippingOptions||[],n=i.find(e=>e.isRecommended),r=(e?i.find(t=>t.id===e):i.find(e=>{var i;return e.id===(null===(i=t.selectedShippingOption)||void 0===i?void 0:i.id)}))||n||i[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,i;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===(i=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===i?void 0:i.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:i}=e,{address:n,name:{full_name:r}}=i[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:n.address_line_1,address2:n.address_line_2,city:n.admin_area_2,countryCode:n.country_code,postalCode:n.postal_code,stateOrProvinceCode:n.admin_area_1})}getValidButtonStyle(e){const{color:t,height:i,label:n,shape:r}=e||{},o={color:t&&os[t]?t:void 0,height:this.getValidHeight(i),label:n&&rs[n]?n:void 0,shape:r&&as[r]?r:void 0};return H(o,k)}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 us=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class hs{constructor(e){this.requestSender=e}createOrder(e,t){return us(this,void 0,void 0,function*(){const i=`/api/storefront/payment/${e}`,n=t,r=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.post(i,{headers:r,body:n})).body})}updateOrder(e){return us(this,void 0,void 0,function*(){const t=e,i=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:i,body:t})).body})}getOrderStatus(e="paypalcommerce",t){return us(this,void 0,void 0,function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body})}}var ps=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ms{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,i,n){return ps(this,void 0,void 0,function*(){const r=this.getPayPalSdkScriptConfigOrThrow(e,t,i);return this.loadPayPalSDK(r,n)})}loadPayPalSDK(e,t=!1){return ps(this,void 0,void 0,function*(){if(!this.window.paypal||t){const t=this.transformConfig(e.options),i=this.transformConfig(e.attributes),n=`https://www.paypal.com/sdk/js?${new URLSearchParams(t).toString()}`;yield this.scriptLoader.loadScript(n,{async:!0,attributes:i})}if(!this.window.paypal)throw new pn;return this.window.paypal})}getPayPalSdkScriptConfigOrThrow(e,t,i=!0){const{id:n,clientToken:r,initializationData:o}=e;if(!(null==o?void 0:o.clientId))throw new Qi(Zi.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:v}=o,f=h||i,S="paypalcommercecreditcards"===n,w=S?["card"]:[],I=p?["credit","paylater"]:[],_=u?["venmo"]:[],C=v?["googlepay"]:[],b=i?["card-fields"]:[],P=[...S?[]:["card"],...p?[]:["credit","paylater"],...u?[]:["venmo"],...y.filter(e=>!g.includes(e))],O=[...w,...I,..._,...g];return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":O.length>0?O:void 0,"disable-funding":P.length>0?P:void 0,commit:f,components:["buttons","hosted-fields","payment-fields","legal",...C,...b],currency:t,intent:a},m&&{"buyer-country":c}),attributes:{"data-partner-attribution-id":l,"data-client-token":r}}}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}const ys=e=>{const{getHost:t}=e.getState();return new ls(Ee(),e,new hs(i({host:t()})),new ms(a()))};var gs=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class vs{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=V}initialize(e){return gs(this,void 0,void 0,function*(){const{paypalcommerce:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.paypalcommerce.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.paypalcommerce.onClick" argument is not a function.');this.onError=t.onError||V,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.paypalCommerceIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 gs(this,void 0,void 0,function*(){return yield this.paymentIntegrationService.signInCustomer(e,t),Promise.resolve()})}signOut(e){return gs(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 i,n;const{container:r,onClick:o,onComplete:a}=t,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{isHostedCheckoutEnabled:c,paymentButtonStyles:l,isAppSwitchEnabled:u}=d.initializationData||{},{checkoutTopButtonStyles:h}=l||{},p=Object.assign(Object.assign(Object.assign({},this.isPaypalCommerceAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommerce"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)}),o&&{onClick:()=>o()}),m=Object.assign(Object.assign({},!u&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(t,i)=>this.onHostedCheckoutApprove(t,i,e,a)}),y=Object.assign(Object.assign({fundingSource:s.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(Object.assign(Object.assign({},h),{height:fr}))},p),c&&m),g=s.Buttons(y);g.isEligible()?(null===(i=g.hasReturned)||void 0===i?void 0:i.call(g))&&this.isPaypalCommerceAppSwitchEnabled(e)?null===(n=g.resume)||void 0===n||n.call(g):g.render(`#${r}`):this.paypalCommerceIntegrationService.removeElement(r)}onHostedCheckoutApprove(e,t,i,n){return gs(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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:i}}),yield this.paypalCommerceIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return gs(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 gs(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)}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}}const fs=Rt(e=>new vs(e,ys(e)),[{id:"paypalcommerce"}]);var Ss=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ws{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=V}initialize(e){return Ss(this,void 0,void 0,function*(){const{paypalcommercecredit:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.paypalcommercecredit.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.paypalcommercecredit.onClick" argument is not a function.');this.onError=t.onError||V,this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.paypalCommerceIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 Ss(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Ss(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:i,onComplete:n,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,i)=>this.onHostedCheckoutApprove(t,i,e,n)}),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:fr}))},u),s&&h),n=o.Buttons(t);n.isEligible()&&(n.render(`#${i}`),m=!0)}}),m||this.paypalCommerceIntegrationService.removeElement(i)}onHostedCheckoutApprove(e,t,i,n){return Ss(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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:i}}),yield this.paypalCommerceIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n()}catch(e){this.handleError(e)}})}onShippingAddressChange(e){return Ss(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 Ss(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 Is=Rt(e=>new ws(e,ys(e)),[{id:"paypalcommercecredit"}]);var _s=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Cs{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return _s(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(!t.container)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo.container" argument is not provided.');if(t.onClick&&"function"!=typeof t.onClick)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo.onClick" argument is not a function.');this.paymentIntegrationService.getState().getPaymentMethod(i)||(yield this.paymentIntegrationService.loadPaymentMethod(i));const n=yield this.paypalCommerceIntegrationService.loadPayPalSdk(i);n&&n.Buttons&&"function"==typeof n.Buttons?this.renderButton(i,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 _s(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return _s(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:i,onClick:n}=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:fr})),createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:t})=>this.paypalCommerceIntegrationService.tokenizePayment(e,t)},n&&{onClick:()=>n()}),c=r.Buttons(d);c.isEligible()?c.render(`#${i}`):this.paypalCommerceIntegrationService.removeElement(i)}}const bs=Rt(e=>new Cs(e,ys(e)),[{id:"paypalcommercevenmo"}]);var Ps,Os,Es,As,Ts,ks,Ds,Ms,zs,Ns,xs=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Fs{constructor(e){this.scriptLoader=e,this.window=window}getPayPalSDK(e,t,i,n){return xs(this,void 0,void 0,function*(){if(!this.window.paypal||n){const n=this.getPayPalSdkScriptConfigOrThrow(e,t,i);if(yield this.loadPayPalSdk(n),!this.window.paypal)throw new pn}return this.window.paypal})}getPayPalFastlaneSdk(e,t,i){return xs(this,void 0,void 0,function*(){if(!this.window.paypalFastlaneSdk){const n=this.getPayPalFastlaneSdkConfiguration(e,t,i);if(yield this.loadPayPalSdk(n),!this.window.paypalFastlaneSdk)throw new pn}return this.window.paypalFastlaneSdk})}getPayPalGooglePaySdk(e,t,i,n){return xs(this,void 0,void 0,function*(){if(!this.window.paypalGooglePay||n){const n=this.getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i);yield this.loadPayPalSdk(n)}if(!this.window.paypalGooglePay)throw new pn;return this.window.paypalGooglePay})}getPayPalApmsSdk(e,t){return xs(this,void 0,void 0,function*(){if(!this.window.paypalApms){const i=this.getPayPalApmSdkConfiguration(e,t);if(yield this.loadPayPalSdk(i),!this.window.paypalApms)throw new pn}return this.window.paypalApms})}getPayPalMessages(e,t){return xs(this,void 0,void 0,function*(){if(!this.window.paypalMessages){const i=this.getPayPalSdkMessagesConfiguration(e,t);yield this.loadPayPalSdk(i)}if(!this.window.paypalMessages)throw new pn;return this.window.paypalMessages})}loadPayPalSdk({options:e,attributes:t}){return xs(this,void 0,void 0,function*(){const i=this.transformConfig(e),n=this.transformConfig(t),r=`https://www.paypal.com/sdk/js?${new URLSearchParams(i).toString()}`;yield this.scriptLoader.loadScript(r,{async:!0,attributes:n})})}getPayPalSdkScriptConfigOrThrow(e,t,i=!0){const{id:n,clientToken:r,initializationData:o}=e;if(!o||!o.clientId)throw new Qi(Zi.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:v}=o,f=h||i,S="paypalcommercecreditcards"===n||"bigcommerce_payments_creditcards"===n,w=S?["card"]:[],I=p?["credit","paylater"]:[],_=u?["venmo"]:[],C=v?["googlepay"]:[],b=i?["card-fields"]:[],P=[...S?[]:["card"],...p?[]:["credit","paylater"],...u?[]:["venmo"],...y.filter(e=>!g.includes(e))],O=[...w,...I,..._,...g];return{options:Object.assign({"client-id":s,"merchant-id":d,"enable-funding":O.length>0?O:void 0,"disable-funding":P.length>0?P:void 0,commit:f,components:["buttons","hosted-fields","payment-fields","legal",...C,...b],currency:t,intent:a},m&&{"buyer-country":c}),attributes:{"data-partner-attribution-id":l,"data-client-token":r}}}getPayPalFastlaneSdkConfiguration(e,t,i){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,attributionId:d}=r;return{options:{"client-id":a,"merchant-id":s,commit:!0,components:["fastlane","buttons","payment-fields","hosted-fields","three-domain-secure"],currency:t,intent:o},attributes:{"data-client-metadata-id":i.replace(/-/g,""),"data-namespace":"paypalFastlaneSdk","data-partner-attribution-id":d,"data-sdk-client-token":n}}}getPayPalGooglePaySdkScriptConfigOrThrow(e,t,i=!0){const{clientToken:n,initializationData:r}=e;if(!r||!r.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:o,clientId:a,merchantId:s,buyerCountry:d,attributionId:c,isHostedCheckoutEnabled:l,isDeveloperModeApplicable:u}=r,h=l||i;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":n,"data-namespace":"paypalGooglePay"}}}getPayPalApmSdkConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{intent:n,clientId:r,merchantId:o,buyerCountry:a,attributionId:s,isDeveloperModeApplicable:d,availableAlternativePaymentMethods:c=[],enabledAlternativePaymentMethods:l=[]}=i,u=l,h=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:n},d&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"paypalApms"}}}getPayPalSdkMessagesConfiguration(e,t){const{initializationData:i}=e;if(!i||!i.clientId)throw new Qi(Zi.MissingPaymentMethod);const{clientId:n,merchantId:r,attributionId:o,isDeveloperModeApplicable:a,buyerCountry:s}=i;return{options:Object.assign({"client-id":n,"merchant-id":r,components:["messages"],currency:t},a&&{"buyer-country":s}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":o}}}transformConfig(e){let t={};return Object.keys(e).forEach(i=>{const n=e[i];null==n||""===n||Array.isArray(n)&&0===n.length||(t=Object.assign(Object.assign({},t),{[i]:Array.isArray(n)?n.join(","):n}))}),t}}function Rs(){return new Fs(o())}!function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Ps||(Ps={})),(Os||(Os={})).Always="SCA_ALWAYS",function(e){e.Succeeded="succeeded",e.Cancelled="cancelled",e.Errored="errored"}(Es||(Es={})),function(e){e.Possible="POSSIBLE",e.No="NO",e.Unknown="UNKNOWN",e.Yes="YES"}(As||(As={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Ts||(Ts={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(ks||(ks={})),function(e){e.pill="pill",e.rect="rect"}(Ds||(Ds={})),function(e){e.SUCCEEDED="succeeded",e.FAILED="failed",e.CANCELED="canceled",e.UNRECOGNIZED="unrecognized"}(Ms||(Ms={})),(zs||(zs={})).OXXO="oxxo",function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED",e.PollingStop="POLLING_STOP",e.PollingError="POLLING_ERROR"}(Ns||(Ns={}));var Ls=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Bs{constructor(){this.window=window}initializePayPalFastlane(e,t,i){return Ls(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:i||t})}return this.window.paypalFastlane})}getPayPalFastlaneOrThrow(){if(!this.window.paypalFastlane)throw new pn;return this.window.paypalFastlane}lookupCustomerOrThrow(e){return Ls(this,void 0,void 0,function*(){return this.getPayPalFastlaneOrThrow().identity.lookupCustomerByEmail(e)})}triggerAuthenticationFlowOrThrow(e){return Ls(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 i={expires:t,secure:!0};Nr.set("bc-fastlane-sessionId",e,i)}removeStorageSessionId(){Nr.remove("bc-fastlane-sessionId")}getStorageSessionId(){return Nr.get("bc-fastlane-sessionId")||""}mapPayPalFastlaneProfileToBcCustomerData(e,t){var i,n,r;const{authenticationState:o,profileData:a}=t,s=null===(r=null===(n=null===(i=null==a?void 0:a.card)||void 0===i?void 0:i.paymentSource)||void 0===n?void 0:n.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||Ms.UNRECOGNIZED,addresses:m,billingAddress:h,shippingAddress:u,instruments:p}}mapPayPalToBcInstrument(e,t){const{id:i,paymentSource:n}=t,{brand:r,expiry:o,lastDigits:a}=n.card,[s,d]=o.split("-");return[{bigpayToken:i,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:_r.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,i,n){const[r,o]=t.fullName.split(" "),a=(null==i?void 0:i.nationalNumber)||"",s=(null==i?void 0:i.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:n||[]}}filterAddresses(e){return e.reduce((e,t)=>t?e.some(e=>this.isEqualAddresses(e,t))?e:[...e,t]:e,[])}isEqualAddresses(e,t){return A(this.normalizeAddress(e),this.normalizeAddress(t))}normalizeAddress(e){return G(e,["id","phone"])}}function js(){return new Bs}function Us(e){return"string"!=typeof e}function qs(e,t){if(t||e)return function(e){var t,i;const n={},r=H(e.root,Us),o=H(e.input,Us),a=H(e.toggle,Us),s=H(null===(t=e.text)||void 0===t?void 0:t.body,Us),d=H(null===(i=e.text)||void 0===i?void 0:i.caption,Us),c=e.branding;return Object.keys(r).length&&(n.root=r),Object.keys(o).length&&(n.input=o),Object.keys(a).length&&(n.toggle=a),Object.keys(s).length&&(n.text={},n.text.body=s),Object.keys(d).length&&(n.text=Object.assign({},n.text),n.text.caption=d),c&&(n.branding=c),n}(function(e,t){var i,n,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,w,I,_,C;return{root:{backgroundColorPrimary:(null==e?void 0:e.fastlaneRootSettingsBackgroundColor)||(null===(i=null==t?void 0:t.root)||void 0===i?void 0:i.backgroundColorPrimary),errorColor:(null==e?void 0:e.fastlaneRootSettingsErrorColor)||(null===(n=null==t?void 0:t.root)||void 0===n?void 0:n.errorColor),fontFamily:(null==e?void 0:e.fastlaneRootSettingsFontFamily)||(null===(r=null==t?void 0:t.root)||void 0===r?void 0:r.fontFamily),fontSizeBase:(null==e?void 0:e.fastlaneRootSettingsFontSize)||(null===(o=null==t?void 0:t.root)||void 0===o?void 0:o.fontSizeBase),padding:(null==e?void 0:e.fastlaneRootSettingsPadding)||(null===(a=null==t?void 0:t.root)||void 0===a?void 0:a.padding),primaryColor:(null==e?void 0:e.fastlaneRootSettingsPrimaryColor)||(null===(s=null==t?void 0:t.root)||void 0===s?void 0:s.primaryColor)},input:{borderRadius:(null==e?void 0:e.fastlaneInputSettingsBorderRadius)||(null===(d=null==t?void 0:t.input)||void 0===d?void 0:d.borderRadius),borderColor:(null==e?void 0:e.fastlaneInputSettingsBorderColor)||(null===(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===(v=null===(g=null==t?void 0:t.text)||void 0===g?void 0:g.body)||void 0===v?void 0:v.color),fontSize:(null==e?void 0:e.fastlaneTextBodySettingsFontSize)||(null===(S=null===(f=null==t?void 0:t.text)||void 0===f?void 0:f.body)||void 0===S?void 0:S.fontSize)},caption:{color:(null==e?void 0:e.fastlaneTextCaptionSettingsColor)||(null===(I=null===(w=null==t?void 0:t.text)||void 0===w?void 0:w.caption)||void 0===I?void 0:I.color),fontSize:(null==e?void 0:e.fastlaneTextCaptionSettingsFontSize)||(null===(C=null===(_=null==t?void 0:t.text)||void 0===_?void 0:_.caption)||void 0===C?void 0:C.fontSize)}},branding:(null==e?void 0:e.fastlaneBrandingSettings)||(null==t?void 0:t.branding)}}(e,t))}var Vs=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Gs{constructor(e,t,i){this.paymentIntegrationService=e,this.paypalSdkScriptLoader=t,this.paypalFastlaneUtils=i}initialize(e){var t;return Vs(this,void 0,void 0,function*(){const{methodId:i,paypalcommercefastlane:n}=e;if(!i)throw new gn('Unable to proceed because "methodId" argument is not provided.');try{yield this.paymentIntegrationService.loadPaymentMethod(i);const e=this.paymentIntegrationService.getState(),r=e.getCartOrThrow(),o=e.getPaymentMethodOrThrow(i),a=!!(null===(t=o.initializationData)||void 0===t?void 0:t.isDeveloperModeApplicable),s=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(o,r.currency.code,r.id);yield this.paypalFastlaneUtils.initializePayPalFastlane(s,a,this.getFastlaneStyles(i,n))}catch(e){}return Promise.resolve()})}deinitialize(){return Vs(this,void 0,void 0,function*(){return Promise.resolve()})}signIn(e,t){return Vs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signInCustomer(e,t)})}signOut(e){return Vs(this,void 0,void 0,function*(){yield this.paymentIntegrationService.signOutCustomer(e)})}executePaymentMethodCheckout(e){return Vs(this,void 0,void 0,function*(){const{checkoutPaymentMethodExecuted:t,continueWithCheckoutCallback:i,methodId:n}=e||{};if(!n)throw new gn('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof i)throw new gn('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(n)}catch(e){}}i()})}runPayPalAuthenticationFlowOrThrow(e){return Vs(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow().id,n=t.getCustomer(),r=t.getBillingAddress(),o=(null==n?void 0:n.email)||(null==r?void 0:r.email)||"",{customerContextId:a}=yield this.paypalFastlaneUtils.lookupCustomerOrThrow(o),s=yield this.paypalFastlaneUtils.triggerAuthenticationFlowOrThrow(a),d=s.authenticationState===Ms.CANCELED;yield this.updateCustomerDataState(e,s),d?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(i)})}updateCustomerDataState(e,t){var i;return Vs(this,void 0,void 0,function*(){const n=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&&n.lineItems.physicalItems.length>0){const t=yield this.paymentIntegrationService.updateShippingAddress(s),n=t.getPaymentMethodOrThrow(e),{isFastlaneShippingOptionAutoSelectEnabled:r}=n.initializationData||{},o=t.getConsignments()||[],a=(null===(i=o[0])||void 0===i?void 0:i.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 i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{fastlaneStyles:n,isFastlaneStylingEnabled:r}=i.initializationData||{};return qs(r?n:{},null==t?void 0:t.styles)}}const Hs=Rt(e=>new Gs(e,Rs(),js()),[{id:"paypalcommerceacceleratedcheckout"},{id:"paypalcommercecreditcards"}]);function $s(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 Ws(e){return"stripeLinkAuthenticationState"in e}class Ys{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){var t,i,n,r,o;return i=this,n=void 0,o=function*(){let i;if(!e.stripeupe)throw new gn('Unable to proceed because "options" argument is not provided.');const{container:n,gatewayId:r,methodId:o,onEmailChange:a,getStyles:s,isLoading:d}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new gn(`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(!$s(l)||!u)throw new Qi(Zi.MissingPaymentToken);const{email:h}=c.getCustomerOrThrow(),p=c.getPaymentProviderCustomerOrThrow(),m=(Ws(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}}}:{},i=yield this.scriptLoader.getStripeClient(l.initializationData,c.getCartLocale(),ba.V3,Da,Ma),this._stripeElements=yield this.scriptLoader.getElements(i,{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()||{},v=g?{defaultValues:{mode:Sa.SHIPPING,email:g}}:{},f=this._stripeElements.getElement(Pa.AUTHENTICATION)||this._stripeElements.create(Pa.AUTHENTICATION,v);f.on(Ea.CHANGE,e=>{if(!("authenticated"in e))throw new Qi(Zi.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)}),f.mount(`#${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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())})}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Pa.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 Ks=Rt(e=>new Ys(e,new ka(a())),[{id:"stripeupe"}]);var Js=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Zs{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,i,n){this.checkoutEventsUnsubscribe=this.paymentIntegrationService.subscribe(()=>Js(this,void 0,void 0,function*(){var r;const o=null==n?void 0:n.getElement(Pa.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=i.onError)||void 0===r||r.call(i,e)))}this.isMounted||(yield null==n?void 0:n.fetchUpdates(),this.mountElement(o,i.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 Vn;var t;throw new Kr}throwDisplayableStripeError(e){if(P(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)}isCancellationError(e){var t;const i=null===(t=null==e?void 0:e.payment_intent.last_payment_error)||void 0===t?void 0:t.message;return!!i&&-1!==i.indexOf("canceled")}throwPaymentConfirmationProceedMessage(){throw new Kr("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 Js(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getPaymentMethodOrThrow(e),{features:r}=i.getStoreConfigOrThrow().checkoutSettings;if(!n.clientToken||!t||!r["PI-626.Block_unnecessary_payment_confirmation_for_StripeUPE"])return!1;const{paymentIntent:o}=yield t.retrievePaymentIntent(n.clientToken);return(null==o?void 0:o.status)===Oa.SUCCEEDED})}mapStripePaymentData(e,t,i=!1){const n=this.paymentIntegrationService.getState().getBillingAddress(),{firstName:r="",lastName:o="",email:a=""}=n||{},s=this._mapStripeAddress(n);if(!e)throw new nn(Xi.PaymentNotInitialized);if(!(a&&s&&s.city&&s.country&&r&&o))throw new Qi(Zi.MissingBillingAddress);return{elements:e,redirect:Ca.IF_REQUIRED,confirmParams:Object.assign({payment_method_data:Object.assign(Object.assign({},i?{allow_redisplay:"always"}:{}),{billing_details:{email:a,address:s,name:`${r} ${o}`}})},t&&{return_url:t})}}isAdditionalActionError(e){return Z(e,{code:"additional_action_required"})}isRedirectAction(e){const{type:t,data:{redirect_url:i}}=e;return"redirect_to_url"===t&&!!i}isOnPageAdditionalAction(e){const{type:t,data:{token:i}}=e;return"additional_action_requires_payment_method"===t&&!!i}updateStripePaymentIntent(e,t){return Js(this,void 0,void 0,function*(){const i=yield this.paymentIntegrationService.loadPaymentMethod(e,{params:{method:t}}),{clientToken:n}=i.getPaymentMethodOrThrow(t);n&&this.scriptLoader.updateStripeElements({clientSecret:n})})}getStripeJsVersion(e){return e.useNewStripeJsVersion?ba.CLOVER:ba.V3}_mapStripeAddress(e){if(e){const{city:t,address1:i,address2:n,countryCode:r,postalCode:o,stateOrProvinceCode:a}=e;return Object.assign({city:t,country:r,postal_code:o,line1:i,line2:n},a?{state:a}:{})}throw new Qi(Zi.MissingBillingAddress)}}const Xs={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},Qs={position:"fixed","background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},ed="embedded-checkout-loading-indicator-rotation";class td{constructor(e){this.styles=Object.assign(Object.assign({},Xs),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=`${ed} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`,e}setStyleAttribute(e,t){Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])})}defineAnimation(){var e;if(document.getElementById(ed))return;const t=document.createElement("style");t.id=ed,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule(`\n @keyframes ${ed} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,0)}}class id{constructor(e){this._decimalPlaces=e}toInteger(e){return Math.round(e*Math.pow(10,this._decimalPlaces))}}const nd=["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 rd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class od{constructor(e,t,i,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=i,this.loadingIndicator=n}initialize(e){return rd(this,void 0,void 0,function*(){const{stripeocs:t}=e||{};if(!t)throw new gn('Unable to proceed because "options" argument is not provided.');const{methodId:i,gatewayId:n,container:r}=t;if(!r||!i||!n)throw new nn(Xi.PaymentNotInitialized);const o=yield this.paymentIntegrationService.loadPaymentMethod(n,{params:{method:i}}),a=o.getPaymentMethodOrThrow(i,n),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!$s(a))throw new Qi(Zi.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);return this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this._mountExpressCheckoutElement(i,r,this._stripeClient,d),Promise.resolve()})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,i,n=40){return rd(this,void 0,void 0,function*(){const r=this._shouldRequireShippingAddress(),o=Object.assign(Object.assign(Object.assign({shippingAddressRequired:r},r?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),r?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ca.AUTO,applePay:Ca.NEVER,googlePay:Ca.NEVER,amazonPay:Ca.NEVER,paypal:Ca.NEVER,klarna:Ca.NEVER},buttonHeight:n}),{cartAmount:a}=this.paymentIntegrationService.getState().getCartOrThrow(),s=Object.assign({mode:"payment",amount:this._toCents(a),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});this._stripeElements=i.elements(s),this._linkV2Element=this._stripeElements.create(Pa.EXPRESS_CHECKOUT,o),this._linkV2Element.mount(`#${t}`),this._initializeEvents(this._linkV2Element,e)})}_initializeEvents(e,t){this._shouldRequireShippingAddress()&&(e.on(Ea.SHIPPING_ADDRESS_CHANGE,e=>rd(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),e.on(Ea.SHIPPING_RATE_CHANGE,e=>rd(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),e.on(Ea.CONFIRM,e=>rd(this,void 0,void 0,function*(){return this._onConfirm(e,t)})),e.on(Ea.CANCEL,this._onCancel)}_onShippingAddressChange(e){return rd(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,i={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(i);const n=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==n?void 0:n.length)?e.resolve({shippingRates:n}):e.reject()})}_onCancel(){throw new Vn}_onShippingRateChange(e){return rd(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 rd(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 i=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(i)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,i,n,r,o,a,s,d;return rd(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(i=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===i?void 0:i.split(" ")[0])||(null===(r=null===(n=e.billingDetails)||void 0===n?void 0:n.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,i,n){var r,o,a,s,d,c,l;return{firstName:i,lastName:n,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,i,n){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:i,lastName:n,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 rd(this,void 0,void 0,function*(){if(!ca(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new nn(Xi.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:n}=i,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(i,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||n);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 i,n,r;return rd(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===(i=this._stripeClient)||void 0===i?void 0:i.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ca.IF_REQUIRED,confirmParams:{return_url:null===(n=s.confirmParams)||void 0===n?void 0:n.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Kr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return rd(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var i;const n=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:n},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:_a.Link})}}}_shouldRequireShippingAddress(){const{getCartOrThrow:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e();return!!t.physicalItems.length}_updateDisplayedPrice(){return rd(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 rd(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:e,getCartOrThrow:t}=this.paymentIntegrationService.getState(),{decimalPlaces:i}=t().currency,n=J(e().outstandingBalance,i).toFixed(i);return this._toCents(+n)})}_getAvailableCountries(){var e;return rd(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=>nd.includes(e))})}_getAvailableShippingOptions(){var e,t;return rd(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const n=i[0],r=(n.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),o=null===(e=n.selectedShippingOption)||void 0===e?void 0:e.id;return o?r.sort(e=>e.id===o?-1:0):yield this._handleShippingOptionChange(null===(t=r[0])||void 0===t?void 0:t.id),r})}_getStripeShippingOption({id:e,cost:t,description:i}){return{id:e,displayName:i,amount:this._toCents(t)}}_handleShippingOptionChange(e){return rd(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 id(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),i=this._getAmountTransformer();return i?i.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}}const ad=Rt(e=>{const t=new ka(a()),i=new td({containerStyles:Qs});return new od(e,t,new Zs(e,t),i)},[{id:"stripeocs"}]);var sd,dd,cd,ld,ud,hd,pd;class md{constructor(e,t,i=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=i}load(e){var t,i,n,r,o,a;return n=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!==(i=e.environment)&&void 0!==i?i:""}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-wG2z9zSQo61EIvyXmiFCo+zB3y0ZB4hsrXVcANmpP8HLthjoQJQPBh7tZKJSV8jA",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new pn;return new this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())})}}function yd(e){return"object"==typeof e&&"string"==typeof e.data.paymentMethod.encryptedSecurityCode||"string"==typeof e.data.paymentMethod.encryptedExpiryMonth}function gd(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"}(sd||(sd={})),function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2Challenge="threeDS2Challenge",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher"}(dd||(dd={})),function(e){e.SecuredFields="securedfields"}(cd||(cd={})),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"}(ld||(ld={})),function(e){e.POST="POST"}(ud||(ud={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(hd||(hd={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(pd||(pd={}));class vd extends Ji{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var fd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Sd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return fd(this,void 0,void 0,function*(){const{adyenv2:t}=e;if(!t)throw new gn('Unable to initialize payment because "options.adyenv2" argument is not provided.');this._paymentInitializeOptions=t;const i=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{originKey:n,clientKey:r,environment:o,paymentMethodsResponse:a}=i.initializationData||{},s={key:"",value:""};return n?(s.key="originKey",s.value=n):(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(i),i.method!==ld.CreditCard&&i.method!==ld.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){return fd(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=i&&i.paymentData,o=r&&r.shouldSaveInstrument,a=r&&r.shouldSetAsDefaultInstrument;if(!i)return Promise.reject(new oo(["payment"]));this._validateCardData(),yield this._paymentIntegrationService.submitOrder(n,t);const s=this._componentState;if(!s)throw new nn(Xi.PaymentNotInitialized);if(r&&gd(r)){let e={};if(yd(s)){const{encryptedCardNumber:t,encryptedSecurityCode:i,encryptedExpiryMonth:n,encryptedExpiryYear:r}=s.data.paymentMethod;e={credit_card_number_confirmation:t,expiry_month:n,expiry_year:r,verification_value:i}}if(yd(s)||-1!==["ideal","sepadirectdebit","directEbanking","giropay"].indexOf(s.data.paymentMethod.type))try{return void(yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:{formattedPayload:{bigpay_token:Object.assign(Object.assign({},e),{token:r.instrumentId}),origin:window.location.origin,browser_info:Xa(),set_as_default_stored_instrument:a||null}}})))}catch(e){return void(yield this._processAdditionalAction(e,o,a))}}try{yield this._paymentIntegrationService.submitPayment({methodId:i.methodId,paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify(Object.assign(Object.assign({},s.data.paymentMethod),{origin:window.location.origin}))},browser_info:Xa(),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 vd)}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 nn(Xi.PaymentNotInitialized);return this._adyenClient}_getPaymentInitializeOptions(){if(!this._paymentInitializeOptions)throw new gn('"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,i)=>{const{threeDS2ContainerId:n,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 i={methodId:c.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};d&&d(),t(i)},size:this._getThreeDS2ChallengeWidgetSize(),onError:e=>i(e)});o&&o(c.type===dd.ThreeDS2Challenge||c.type===dd.QRCode),l.mount(`#${a||n}`),s&&s(()=>{i(new Vn),l.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:i,lastName:n,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${i} ${n}`:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let i;return new Promise((n,r)=>{var o,a,s;if(e.cardVerificationContainerId){i=t.create(cd.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{i.mount(`#${e.cardVerificationContainerId}`)}catch(e){r(new nn(Xi.PaymentNotInitialized))}}n(i)})}_mountPaymentComponent(e){let t;const i=this._getPaymentInitializeOptions(),n=this._getAdyenClient();return new Promise((r,o)=>{switch(e.method){case ld.CreditCard:case ld.ACH:case ld.Bancontact:{const r=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:a}=e.initializationData;t=n.create(e.method,Object.assign(Object.assign({},i.options),{onChange:e=>this._updateComponentState(e),data:this._mapAdyenPlaceholderData(r,a)}));try{t.mount(`#${i.containerId}`)}catch(e){o(new nn(Xi.PaymentNotInitialized))}break}case ld.IDEAL:case ld.SEPA:if(i.hasVaultedInstruments)this._updateComponentState({data:{paymentMethod:{type:e.method}}});else{t=n.create(e.method,Object.assign(Object.assign({},i.options),{onChange:e=>this._updateComponentState(e)}));try{t.mount(`#${i.containerId}`)}catch(e){o(new nn(Xi.PaymentNotInitialized))}}break;case ld.AliPay:case ld.GiroPay:case ld.Sofort:case ld.Klarna:case ld.KlarnaPayNow:case ld.KlarnaAccount:case ld.Vipps:case ld.WeChatPayQR:this._updateComponentState({data:{paymentMethod:{type:e.method}}})}r(t)})}_processAdditionalAction(e,t,i){return fd(this,void 0,void 0,function*(){if(!ca(e)||!Z(e.body.errors,{code:"additional_action_required"}))throw e;const n=yield this._handleAction(e.body.provider_data);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:Object.assign(Object.assign({},n.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:i})}))}catch(e){return this._processAdditionalAction(e,t,i)}})}_updateComponentState(e){this._componentState=e}_validateCardData(){var e,t;const i=this._getPaymentInitializeOptions().hasVaultedInstruments?this._cardVerificationComponent:this._paymentComponent;if((null===(e=null==i?void 0:i.componentRef)||void 0===e?void 0:e.showValidation)&&i.state&&(i.componentRef.showValidation(),0===Object.keys(i.state).length||!i.state.isValid&&!i.state.issuer||"sepadirectdebit"===(null===(t=i.props)||void 0===t?void 0:t.type)&&i.state.data&&Object.values(i.state.data).some(e=>0===e.toString().trim().length)))throw new ao(this._mapCardErrors(i.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(i=>{t[i]=[{message:e[i],type:i}]}),t}}const wd=Rt(e=>new Sd(e,new md(a(),s())),[{gateway:"adyenv2"}]);class Id{constructor(e,t,i=window){this._scriptLoader=e,this._stylesheetLoader=t,this._window=i}load(e){var t,i,n,r,o,a;return n=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!==(i=e.environment)&&void 0!==i?i:""}.adyen.com/checkoutshopper/sdk/5.71.1/adyen.js`,{async:!0,attributes:{integrity:"sha384-yvY2yFNR4WqIjPqP9MzjI+gJimmaJnAvj4rLHKvgJbgFD5fMuf8zIJrFJOW8Lhhf",crossorigin:"anonymous"}})]),!this._window.AdyenCheckout)throw new pn;return yield this._window.AdyenCheckout(e)},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())})}}function _d(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}var Cd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class bd{constructor(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}initialize(e){return Cd(this,void 0,void 0,function*(){const{adyenv3:t}=e;if(!t)throw new gn('Unable to initialize payment because "options.adyenv3" argument is not provided.');this._paymentInitializeOptions=t;const i=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),{environment:n,clientKey:r,paymentMethodsResponse:o,installmentOptions:a}=i.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:n,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(i),i.method!==ld.CreditCard&&i.method!==ld.Bancontact||(this._cardVerificationComponent=yield this._mountCardVerificationComponent()),Promise.resolve()})}execute(e,t){var i;return Cd(this,void 0,void 0,function*(){const{payment:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!n)throw new oo(["payment"]);const o=n.paymentData,{shouldSaveInstrument:a,shouldSetAsDefaultInstrument:s}=_d(o)?o:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};this._validateCardData(),"klarna"!==n.methodId&&"klarna_account"!==n.methodId&&"klarna_paynow"!==n.methodId||null===(i=this._paymentComponent)||void 0===i||i.submit(),yield this._paymentIntegrationService.submitOrder(r,t);const d=this._componentState||{data:{paymentMethod:{type:n.methodId}}};if(o&&gd(o)){let e={};if(yd(d)){const{encryptedCardNumber:t,encryptedSecurityCode:i,encryptedExpiryMonth:n,encryptedExpiryYear:r}=d.data.paymentMethod;e={credit_card_number_confirmation:t,expiry_month:n,expiry_year:r,verification_value:i}}try{return void(yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},n),{paymentData:{formattedPayload:{bigpay_token:Object.assign(Object.assign({},e),{token:o.instrumentId}),origin:window.location.origin,browser_info:Xa(),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:n.methodId,origin:window.location.origin}));"boletobancario"===n.methodId&&function(e){var t,i;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===(i=e.data.shopperName)||void 0===i?void 0:i.lastName)}(d)&&(c=JSON.stringify(Object.assign(Object.assign({socialSecurityNumber:d.data.socialSecurityNumber},d.data.shopperName),{type:n.methodId,origin:window.location.origin})));try{yield this._paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:{formattedPayload:Object.assign(Object.assign({credit_card_token:{token:c}},yd(d)&&d.data.installments?{installments:{value:d.data.installments.value,plan:d.data.installments.plan||"regular"}}:{}),{browser_info:Xa(),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 vd)}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 nn(Xi.PaymentNotInitialized);return this._adyenClient}_getPaymentInitializeOptions(){if(!this._paymentInitializeOptions)throw new gn('"options.adyenv3" argument was not provided during initialization.');return this._paymentInitializeOptions}_handleAction(e){return new Promise((t,i)=>{const{additionalActionOptions:n}=this._getPaymentInitializeOptions(),{onBeforeLoad:r,containerId:o,onLoad:a,onComplete:s,widgetSize:d,onActionHandled:c}=n,l=JSON.parse(e.action),u=this._getAdyenClient().createFromAction(l,{onActionHandled:e=>{c&&"function"==typeof c&&"3DS2Fingerprint"!==e.componentType&&c()},onAdditionalDetails:e=>{const i={methodId:l.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};s&&"function"==typeof s&&s(),t(i)},challengeWindowSize:d||"05",onError:e=>i(e)});r&&"function"==typeof r&&r(l.type===sd.ThreeDS2||l.type===sd.QRCode||l.type===sd.Sdk),this._mountElement(u,o),a&&"function"==typeof a&&a(()=>{i(new Vn),u.unmount()})})}_mapAdyenPlaceholderData(e,t){if(!e)return{};const{firstName:i,lastName:n,address1:r,address2:o,postalCode:a,city:s,stateOrProvinceCode:d,countryCode:c}=e;return{holderName:t?`${i} ${n}`:"",firstName:t?i:"",lastName:t?n:"",billingAddress:{street:r,houseNumberOrName:o,postalCode:a,city:s,stateOrProvince:d,country:c}}}_mountCardVerificationComponent(){const e=this._getPaymentInitializeOptions(),t=this._getAdyenClient();let i;return new Promise((n,r)=>{var o,a,s;if(e.cardVerificationContainerId){i=t.create(cd.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(i,e.cardVerificationContainerId)}catch(e){r(new nn(Xi.PaymentNotInitialized))}}n(i)})}_mountPaymentComponent(e){let t;const i=this._getPaymentInitializeOptions(),n=this._getAdyenClient();return new Promise((r,o)=>{const a=this._paymentIntegrationService.getState().getBillingAddress(),{prefillCardHolderName:s}=e.initializationData;t=n.create(e.method,Object.assign(Object.assign(Object.assign({},i.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,i.containerId)}catch(e){o(new nn(Xi.PaymentNotInitialized))}r(t)})}_processAdditionalAction(e,t,i,n,r){return Cd(this,void 0,void 0,function*(){if(!ca(e)||!Z(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:i}),a=i&&!t?{instrumentId:n,formattedPayload:{bigpay_token:Object.assign(Object.assign({},r),{token:n})}}:{};yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},o),{paymentData:Object.assign(Object.assign({},e),a)}))}catch(e){return this._processAdditionalAction(e,t,i,n,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 ao(this._mapCardErrors(t.state.errors))}_mapCardErrors(e={}){const t={};return Object.keys(e).forEach(i=>{t[i]=[{message:e[i],type:i}]}),t}_mountElement(e,t){document.getElementById(t)&&e.mount(`#${t}`)}}const Pd=Rt(e=>new bd(e,new Id(a(),s())),[{gateway:"adyenv3"}]);var Od,Ed=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ad{constructor(e,t){this.paymentIntegrationService=e,this.affirmScriptLoader=t}initialize(e){return Ed(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e.methodId);const t=this.paymentIntegrationService.getState(),{clientToken:i,config:{testMode:n}}=t.getPaymentMethodOrThrow(e.methodId);if(!i)throw new Qi(Zi.MissingPaymentMethod);this.affirm=yield this.affirmScriptLoader.load(i,n)})}execute(e,t){var i;return Ed(this,void 0,void 0,function*(){const n=null===(i=e.payment)||void 0===i?void 0:i.methodId,{useStoreCredit:r}=e;if(!this.affirm)throw new nn(Xi.PaymentNotInitialized);if(!n)throw new oo(["payment.methodId"]);yield this.paymentIntegrationService.submitOrder({useStoreCredit:r},t);const o={methodId:n,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 vd)}initializeAffirmCheckout(){var e;return null===(e=this.affirm)||void 0===e||e.checkout(this.getCheckoutInformation()),new Promise((e,t)=>{var i,n;null===(i=this.affirm)||void 0===i||i.checkout.open({onFail:e=>{"canceled"===e.reason?t(new Vn):t(new Jr)},onSuccess:t=>{e(t)}}),null===(n=this.affirm)||void 0===n||n.ui.error.on("close",()=>{t(new Vn)})})}getCheckoutInformation(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfig(),i=e.getConsignments(),n=e.getOrder(),r=e.getCart();if(!t)throw new Qi(Zi.MissingCheckoutConfig);if(!n)throw new Qi(Zi.MissingCheckout);const o=new id(n.currency.decimalPlaces),a=this.getBillingAddress(),s=this.getShippingAddress(),d=Ro(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,n),metadata:{shipping_type:this.getShippingType(i),mode:"modal",platform_type:"BigCommerce",platform_version:"",platform_affirm:""},discounts:this.getDiscounts(o,n),order_id:n.orderId?n.orderId.toString():"",shipping_amount:o.toInteger(n.shippingCostTotal),tax_amount:o.toInteger(n.taxTotal),total:o.toInteger(n.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 Qi(Zi.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 i=[];return t.lineItems.physicalItems.forEach(t=>{i.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=>{i.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=>{i.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=>{i.push({display_name:t.name,sku:t.sku,unit_price:e.toInteger(t.listPrice),qty:t.quantity,item_image_url:"",item_url:""})}),i}getDiscounts(e,t){const i={};return t.coupons.forEach(t=>{t.discountedAmount>0&&(i[t.code]={discount_amount:e.toInteger(t.discountedAmount),discount_display_name:t.displayName})}),t.discountAmount>0&&(i.DISCOUNTED_AMOUNT={discount_amount:e.toInteger(t.discountAmount),discount_display_name:"discount"}),i}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"}(Od||(Od={}));class Td{constructor(e=window){this.affirmWindow=e}load(e="",t){const i=t?Od.SANDBOX:Od.PROD;if(function(e,t,i,n,r,o,a){const s=e[i]||{},d=document.createElement(o),c=document.getElementsByTagName(o)[0],l=function(e,t,i){return function(){e[t]._.push([i,arguments])}};s[n]=l(s,n,"set");const u=s[n];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,n,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[i]=s}(window,{public_api_key:e,script:i},"affirm","checkout","ui","script","ready"),!this.affirmWindow.affirm)throw new pn;return Promise.resolve(this.affirmWindow.affirm)}}const kd=Rt(e=>new Ad(e,new Td),[{id:"affirm"}]);class Dd extends Ji{constructor(e){super(e||"The current order could not be finalized successfully"),this.name="OrderFinalizationNotCompletedError",this.type="order_finalization_not_completed"}}var Md=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class zd{constructor(e,t){this._paymentIntegrationService=e,this._afterpayScriptLoader=t}initialize(e){var t;return Md(this,void 0,void 0,function*(){const i=this._paymentIntegrationService.getState(),n=i.getPaymentMethod(e.methodId,e.gatewayId),r=(null===(t=i.getCart())||void 0===t?void 0:t.currency.code)||"",o=this._mapCurrencyToISO2(r),a=Wt(i.getStoreConfigOrThrow().checkoutSettings.features,"PI-4789.afterpay_script_use_https",!1);if(!n)throw new Qi(Zi.MissingPaymentMethod);this._afterpaySdk=yield this._afterpayScriptLoader.load(n,o,a)})}deinitialize(){return this._afterpaySdk&&(this._afterpaySdk=void 0),Promise.resolve()}execute(e,t){var i;return Md(this,void 0,void 0,function*(){if(!e.payment)throw new oo(["payment.gatewayId","payment.methodId"]);const{gatewayId:n,methodId:r}=e.payment;if(!n||!r)throw new oo(["payment.gatewayId","payment.methodId"]);const{useStoreCredit:o}=e;void 0!==o&&(yield this._paymentIntegrationService.applyStoreCredit(o)),yield this._loadPaymentMethod(n,r,t);const a=this._paymentIntegrationService.getState();yield this._paymentIntegrationService.validateCheckout(a.getCheckout(),t);const s=(null===(i=a.getCart())||void 0===i?void 0:i.currency.code)||"",d=this._mapCurrencyToISO2(s);return this._redirectToAfterpay(d,a.getPaymentMethod(r,n)),new Promise(()=>{})})}finalize(e){var t,i,n;return Md(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new Qi(Zi.MissingCheckout);if(!(null==a?void 0:a.payment.token))throw new Qi(Zi.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(),ca(e))throw new Dd(null===(n=null===(i=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===i?void 0:i[0])||void 0===n?void 0:n.message)}})}_redirectToAfterpay(e,t){if(!this._afterpaySdk||!(null==t?void 0:t.clientToken))throw new nn(Xi.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,i){var n;return Md(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},i),{params:Object.assign(Object.assign({},null==i?void 0:i.params),{method:t})}))}catch(e){if(e instanceof Qn&&422===(null===(n=e.body)||void 0===n?void 0:n.status))throw new gn("Afterpay can't process your payment for this order, please try another payment method");throw e}})}}var Nd,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"}(Nd||(Nd={})),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 Fd{constructor(e){this._scriptLoader=e}load(e,t,i=!1){return n=this,r=void 0,a=function*(){const n=e.config.testMode||!1,r=this._getScriptURI(t,n,i);return this._scriptLoader.loadScript(r).then(()=>{if(!function(e){return"AfterPay"in e}(window))throw new pn;return window.AfterPay})},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())});var n,r,o,a}_getScriptURI(e,t,i=!1){return"US"===e?i?t?xd.HTTPS_SANDBOX:xd.HTTPS_PROD:t?xd.SANDBOX:xd.PROD:i?t?Nd.HTTPS_SANDBOX:Nd.HTTPS_PROD:t?Nd.SANDBOX:Nd.PROD}}const Rd=Rt(e=>new zd(e,new Fd(o())),[{gateway:"afterpay"},{id:"afterpay"}]);var Ld=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Bd{constructor(e,t){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t}initialize(e){return Ld(this,void 0,void 0,function*(){const{methodId:t,amazonpay:i}=e;if(!t)throw new gn('Unable to proceed because "methodId" argument is not provided.');const n=this.paymentIntegrationService.getState(),{features:r}=n.getStoreConfigOrThrow().checkoutSettings,o=n.getPaymentMethodOrThrow(t),a=o.initializationData||{},{paymentToken:s="",region:d="",isButtonMicroTextDisabled:c}=a;if(yield this.amazonPayV2PaymentProcessor.initialize(o),this._isReadyToPay(s))(null==i?void 0:i.editButtonId)&&this._bindEditButton(i.editButtonId,s,"changePayment",this._isModalFlow(d));else{const{id:e}=this._createContainer();if(this._amazonPayButton=this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:n,containerId:e,decoupleCheckoutInitiation:this._isOneTimeTransaction(r,d.toUpperCase()),methodId:t,placement:an.Checkout,isButtonMicroTextDisabled:c}),!this._amazonPayButton)throw new gn("Unable to render the Amazon Pay button to an invalid HTML container element.")}})}execute(e,t){return Ld(this,void 0,void 0,function*(){const{payment:i}=e;if(!i)throw new oo(["payment"]);const{methodId:n}=i,r=this.paymentIntegrationService.getState(),{features:o}=r.getStoreConfigOrThrow().checkoutSettings,a=r.getPaymentMethodOrThrow(n).initializationData||{},{paymentToken:s="",region:d=""}=a;if(this._isReadyToPay(s)||this._isOneTimeTransaction(o,d.toUpperCase())){const i={methodId:n,paymentData:{nonce:s||"apb"}};yield this.paymentIntegrationService.submitOrder(e,t);try{return void(yield this.paymentIntegrationService.submitPayment(i))}catch(e){if(!(ca(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:i}=t.data;if(s)return new Promise(()=>window.location.assign(i));this.amazonPayV2PaymentProcessor.prepareCheckout(JSON.parse(i))}}var c;return this._getAmazonPayButton().click(),this._isModalFlow(d)?new Promise((e,t)=>{const i=()=>{window.removeEventListener("focus",i),t(new Vn("Shopper needs to login to Amazonpay to continue"))};window.addEventListener("focus",i)}):new Promise(V)})}finalize(){return Promise.reject(new vd)}deinitialize(){return Ld(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize(),this._amazonPayButton=void 0})}_bindEditButton(e,t,i,n){const r=document.getElementById(e);if(r&&r.parentNode){if(!n){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>{this._showLoadingSpinner()})}this.amazonPayV2PaymentProcessor.bindButton(e,t,i)}}_isModalFlow(e){return"us"===e}_showLoadingSpinner(){return Ld(this,void 0,void 0,function*(){yield this.paymentIntegrationService.widgetInteraction(()=>new Promise(V))})}_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 tn(this._amazonPayButton,()=>new nn(Xi.PaymentNotInitialized))}_isOneTimeTransaction(e,t){return this.amazonPayV2PaymentProcessor.isPh4Enabled(e,t)&&e["INT-6399.amazon_pay_apb"]}_isReadyToPay(e){return!!e}}const jd=Rt(e=>new Bd(e,yn()),[{id:"amazonpay"}]);var Ud,qd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e.Shipping="Shipping",e.Subtotal="Subtotal",e.StoreCredit="Store Credit"}(Ud||(Ud={}));class Vd{constructor(e,t,i,n,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=i,this._braintreeSdk=n,this._applePayScriptLoader=r,this._shippingLabel=Ud.Shipping,this._subTotalLabel=Ud.Subtotal,this._storeCreditLabel=Ud.StoreCredit}initialize(e){var t,i,n,r;return qd(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new gn('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)||Ud.Shipping,this._subTotalLabel=(null===(i=e.applepay)||void 0===i?void 0:i.subtotalLabel)||Ud.Subtotal,this._storeCreditLabel=(null===(n=e.applepay)||void 0===n?void 0:n.storeCreditLabel)||Ud.StoreCredit;const a=(yield this._paymentIntegrationService.loadPaymentMethod(o)).getPaymentMethodOrThrow(o);(null===(r=a.initializationData)||void 0===r?void 0:r.gateway)===jn.BRAINTREE&&a.clientToken&&this._braintreeSdk.initialize(a.clientToken)})}execute(e,t){return qd(this,void 0,void 0,function*(){const{payment:i}=e,n=this._paymentIntegrationService.getState();if(!i)throw new oo(["payment"]);const{methodId:r}=i,o=n.getPaymentMethodOrThrow(r),a=this._getBaseRequest(n,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 vd)}deinitialize(){return Promise.resolve()}_getBaseRequest(e,t){const i=e.getCheckoutOrThrow(),n=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),{storeProfile:{storeCountryCode:o,storeName:a}}=r,{currency:{code:s,decimalPlaces:d}}=n,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=t,{grandTotal:u,isStoreCreditApplied:h,outstandingBalance:p}=i,m=[{label:this._subTotalLabel,amount:`${i.subtotal.toFixed(d)}`}];if(i.taxes.forEach(e=>m.push({label:e.name,amount:`${e.amount.toFixed(d)}`})),m.push({label:this._shippingLabel,amount:`${i.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,i){e.onvalidatemerchant=i=>qd(this,void 0,void 0,function*(){try{const{body:n}=yield this._onValidateMerchant(t,i);e.completeMerchantValidation(n)}catch(e){throw new Error("Merchant validation failed")}}),e.oncancel=()=>qd(this,void 0,void 0,function*(){return i.reject(new Vn("Continue with applepay"))}),e.onpaymentauthorized=n=>this._onPaymentAuthorized(n,e,t,i)}_onValidateMerchant(e,t){return qd(this,void 0,void 0,function*(){const i=[`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:i})})}_onPaymentAuthorized(e,t,i,n){var r;return qd(this,void 0,void 0,function*(){const{token:o}=e.payment;let a;(null===(r=i.initializationData)||void 0===r?void 0:r.gateway)===jn.BRAINTREE&&(a=yield this._getBraintreeDeviceData());const s={methodId:i.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),n.resolve()}catch(e){return t.completePayment(ApplePaySession.STATUS_FAILURE),n.reject(new nn(Xi.PaymentNotInitialized))}})}_getBraintreeDeviceData(){return qd(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const Gd=Rt(e=>{const{getHost:t}=e.getState(),n=new bn(e);return new Vd(i({host:t()}),e,new Yn,new Ln(new qn(a(),window,n)),new Kn(new r))},[{id:"applepay"}]),Hd={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},$d=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 Wd(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 Yd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Kd{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.paypalSdkHelper=i,this.loadingIndicator=n}initialize(e){return Yd(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments:i}=e||{};if(this.bigcommerce_payments=i,!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(t),{container:o,bannerContainerId:a}=i,{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,n.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),i.onInit&&"function"==typeof i.onInit&&i.onInit(()=>this.renderButton(t,i)),(void 0===i.shouldRenderPayPalButtonOnInitialization||i.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(t,i))})}execute(e,t){return Yd(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{onError:r}=this.bigcommerce_payments||{};if(!i)throw new oo(["payment"]);const{methodId:o,paymentData:a}=i;if(this.isPayPalVaultedInstrumentPaymentData(a)&&!this.orderId&&(this.orderId=yield this.createOrder()),!this.orderId)throw new Jr;const s=this.isPayPalVaultedInstrumentPaymentData(a)?this.prepareVaultedInstrumentPaymentPayload(o,this.orderId,a):this.preparePaymentPayload(o,this.orderId,a);try{yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment(s)}catch(e){return this.isProviderError(e)&&(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i.methodId),yield new Promise((e,t)=>{var n;this.bigcommerce_payments&&(null===(n=this.paypalButton)||void 0===n||n.close(),this.renderButton(i.methodId,this.bigcommerce_payments),this.handleError(new Error("INSTRUMENT_DECLINED"),r)),t()})),this.handleError(e,r),Promise.reject()}})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,i){const{instrumentId:n,shouldSetAsDefaultInstrument:r}=i,o=!this.isTrustedVaultingFlow(i);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:n,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:n}}}}}preparePaymentPayload(e,t,i){const{shouldSaveInstrument:n=!1,shouldSetAsDefaultInstrument:r=!1}=_d(i)?i:{};return{methodId:e,paymentData:{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=n.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t;if(!a)throw new gn('Unable to initialize payment because "container" argument is not provided.');const u={fundingSource:i.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),createOrder:()=>this.createOrder(),onClick:(e,t)=>this.handleClick(t,c),onApprove:e=>this.handleApprove(e,l),onError:e=>this.handleError(e,s),onCancel:()=>this.toggleLoadingIndicator(!1)};this.paypalButton=i.Buttons(u),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}handleClick(e,t){return Yd(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;yield null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return Yd(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&&gd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),i=null==t?void 0:t.find(t=>Wd(t)&&t.bigpayToken===e.instrumentId);return!(Wd(i)&&!i.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&gd(e)&&_d(e)}renderMessages(e,t,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:$d(i)};e.Messages(n).render(`#${t}`)}isProviderError(e){var t,i,n;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(n=null===(i=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===i?void 0:i.provider_error)||void 0===n?void 0:n.code)}}const Jd=Rt(e=>new Kd(e,vr(e),zr(),new td({containerStyles:Hd})),[{id:"bigcommerce_payments"}]);function Zd(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var Xd=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Qd{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsRequestSender=t,this.bigCommercePaymentsSdk=i,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){var t,i;return Xd(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_fastlane:r}=e;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(this.methodId=n,!r)throw new gn('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 gn('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 gn('Unable to initialize payment because "options.bigcommerce_payments_fastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(n),{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=Br(c?null===(i=null==s?void 0:s.initializationData)||void 0===i?void 0:i.fastlaneStyles:{},null==r?void 0:r.styles);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(n)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(n))})}execute(e,t){return Xd(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{paymentData:r,methodId:o}=i,a=r&&gd(r);try{yield this.paymentIntegrationService.submitOrder(n,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 vd)}deinitialize(){return Xd(this,void 0,void 0,function*(){return Promise.resolve()})}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getCustomerOrThrow(),n=e.getPaymentProviderCustomer(),r=Zd(n)?n:{},o=this.bigCommercePaymentsFastlaneUtils.getStorageSessionId();return!(!i.isGuest||(null==r?void 0:r.authenticationState)===kr.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}runPayPalAuthenticationFlowOrThrow(e){return Xd(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getCustomer(),r=t.getBillingAddress(),o=(null==n?void 0:n.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===kr.CANCELED?this.bigCommercePaymentsFastlaneUtils.removeStorageSessionId():this.bigCommercePaymentsFastlaneUtils.updateStorageSessionId(i.id)}catch(e){}})}initializePayPalPaymentComponent(){return Xd(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),t=e.phone,i=`${e.firstName} ${e.lastName}`.trim(),n=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),r={fields:Object.assign({cardholderName:{prefill:i,enabled:!0}},t&&{phoneNumber:{prefill:t}})};this.paypalComponentMethods=yield n.FastlaneCardComponent(r)})}renderPayPalPaymentComponent(e){const t=this.getPayPalComponentMethodsOrThrow();if(!e)throw new gn('Unable to render card component because "container" argument is not provided.');t.render(e)}getPayPalComponentMethodsOrThrow(){if(!this.paypalComponentMethods)throw new pn;return this.paypalComponentMethods}prepareVaultedInstrumentPaymentPayload(e,t){return Xd(this,void 0,void 0,function*(){const{instrumentId:i}=t,n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),r=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&n.config.is3dsEnabled?yield this.get3DSNonce(i):i;return yield this.createOrder(r),{methodId:e,paymentData:{formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:r}}}}})}preparePaymentPayload(e,t){return Xd(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getBillingAddressOrThrow(),r=i.getPaymentMethodOrThrow(e),o=`${n.firstName} ${n.lastName}`.trim(),{getPaymentToken:a}=this.getPayPalComponentMethodsOrThrow(),{id:s}=yield a({name:{fullName:o},billingAddress:this.bigCommercePaymentsFastlaneUtils.mapBcToPayPalAddress(n)}),d=this.isBigcommercePaymentsFastlaneThreeDSAvailable()&&r.config.is3dsEnabled,{shouldSaveInstrument:c=!1,shouldSetAsDefaultInstrument:l=!1}=_d(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 Xd(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getCartOrThrow().id;if(this.methodId){const{orderId:i}=yield this.bigCommercePaymentsRequestSender.createOrder(this.methodId,{cartId:t,fastlaneToken:e});this.orderId=i}})}get3DSNonce(e){var t;return Xd(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getCartOrThrow(),r=i.getOrderOrThrow(),o=i.getStoreConfigOrThrow().links.checkoutLink,a=null===(t=this.paypalFastlaneSdk)||void 0===t?void 0:t.ThreeDomainSecureClient;if(!a)throw new pn;const s={amount:r.orderAmount.toFixed(2),currency:n.currency.code,nonce:e,threeDSRequested:this.threeDSVerificationMethod===Pr.Always,transactionContext:{experience_context:{locale:"en-US",return_url:o,cancel_url:o}}},d=yield a.isEligible(s);if(this.threeDSVerificationMethod===Pr.Always&&!d)throw new Jr;if(d){const{liabilityShift:e,authenticationState:t,nonce:i}=yield a.show();if(e===er.No||e===er.Unknown||t===Or.Errored||t===Or.Cancelled)throw new Jr;if(t===Or.Succeeded&&[er.Yes,er.Possible].includes(e))return i}return e})}handlePayPalStoredInstrumentChange(e){return Xd(this,void 0,void 0,function*(){const t=this.bigCommercePaymentsFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:i,selectedCard:n}=yield t.profile.showCardSelector();if(i){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),i=Zd(t)?t:{},r=this.bigCommercePaymentsFastlaneUtils.mapPayPalToBcInstrument(e,n)[0];return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},i),{instruments:[r]})),r}})}isBigcommercePaymentsFastlaneThreeDSAvailable(){return Wt(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 ec=Rt(e=>{const{getHost:t}=e.getState();return new Qd(e,new mr(i({host:t()})),zr(),Rr())},[{id:"bigcommerce_payments_fastlane"}]);var tc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ic{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i,this.paypalSdkHelper=n}initialize(e){return tc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_paylater:i}=e||{};if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(t),{paypalBNPLConfiguration:o=[],orderId:a}=r.initializationData||{},{bannerContainerId:s,container:d}=i;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,n.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,i))})}execute(e,t){return tc(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);if(!this.orderId)throw new Jr;yield this.paymentIntegrationService.submitOrder(n,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new vd)}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 gn('Unable to initialize payment because "container" argument is not provided.');const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=n.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u=[i.FUNDING.PAYLATER,i.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=i.Buttons(t),this.bigCommercePaymentsButtons.isEligible()||e!==i.FUNDING.PAYLATER){if(!this.bigCommercePaymentsButtons.isEligible()&&e===i.FUNDING.CREDIT)throw new vn(`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 tc(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;t&&"function"==typeof t&&(yield t(()=>(this.toggleLoadingIndicator(!0),i()),n))})}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,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:$d(i)};e.Messages(n).render(`#${t}`)}}const nc=Rt(e=>new ic(e,vr(e),new td({containerStyles:Hd}),zr()),[{id:"bigcommerce_payments_paylater"}]);class rc extends Qn{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}var oc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ac{constructor(e,t,i,n=3e3,r=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i,this.pollingInterval=n,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=V}initialize(e){return oc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,bigcommerce_payments_ratepay:n}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_ratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=n;if(!o)throw new gn('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new gn('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,t),{merchantId:d}=s.initializationData||{};if(!d)throw new gn("Unable to initialize payment because merchantId argument is not provided.");this.bigcommerce_payments_ratepay=n,yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(i),this.createFraudNetScript(d,i,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return oc(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{getFieldsValues:r}=this.bigcommerce_payments_ratepay||{};if(!i)throw new oo(["payment"]);if(!r||"function"!=typeof r)throw new gn('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:i.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(n,t),yield this.paymentIntegrationService.submitPayment({methodId:i.methodId,paymentData:d}),yield new Promise((e,t)=>{this.initializePollingMechanism(i.methodId,e,t,i.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new vd)}deinitialize(){const{legalTextContainer:e}=this.bigcommerce_payments_ratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],i=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),i.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),i=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${i}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const i=e,n=t.split("#")[1],r=document.getElementById(n),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",i),null==o||o.prepend(a);const s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(i))throw new gn('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${i}`)}handleError(e){const{onError:t}=this.bigcommerce_payments_ratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,i){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,i),{testMode:r}=n.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 oc(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,i,n){return oc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus("bigcommerce_payments_apms",{params:{useMetadata:!0}}),o=r===ar.PollingStop,a=r===ar.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return i();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,bigcommerce_payments_ratepay:this.bigcommerce_payments_ratepay}),this.handleError(new rc)}catch(e){this.handleError(e),i()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const sc=Rt(e=>new ac(e,vr(e),new td({containerStyles:Object.assign(Object.assign({},Hd),{position:"fixed"})})),[{gateway:"bigcommerce_payments_apms",id:"ratepay"}]);var dc;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification",e.CardExpiryVerification="cardExpiryVerification"}(dc||(dc={}));const cc=dc;function lc(e){return cc.CardNumber in e&&cc.CardName in e&&cc.CardExpiry in e}function uc(e){return cc.CardNumberVerification in e&&cc.CardCodeVerification in e&&cc.CardExpiryVerification in e}var hc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class pc{constructor(e,t,i,n){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdk=i,this.bigCommercePaymentsFastlaneUtils=n}initialize(e){return hc(this,void 0,void 0,function*(){const{methodId:t,bigcommerce_payments_creditcards:i}=e,n=i,{form:r,onCreditCardFieldsRenderingError:o,onLoadComplete:a}=n||{};if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new gn('Unable to proceed because "options.bigcommerce_payments_creditcards.form" argument is not provided.');this.hostedFormOptions=r,this.isCreditCardForm=lc(r.fields),this.isCreditCardVaultedForm=uc(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 hc(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{methodId:r,paymentData:o}=i||{};if(!i||!r)throw new oo(["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(n,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e,t,i,n;return hc(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===(i=this.numberField)||void 0===i?void 0:i.close(),yield null===(n=this.nameField)||void 0===n?void 0:n.close(),Promise.resolve()})}preparePaymentPayload(e,t,i,n){const{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=_d(t)?t:{},a=t&&gd(t)?t.instrumentId:void 0,s=H({verification_nonce:n,token:a},k);return{methodId:e,paymentData:{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o,instrumentId:a,formattedPayload:Object.assign(Object.assign({},n||a?{bigpay_token:s}:{}),i?{card_with_order:{order_id:i}}:{})}}}initializeFields(e,t){return hc(this,void 0,void 0,function*(){const{fields:i,styles:n}=e,r=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),o=this.getExecuteCallback(i),a=Object.assign({style:this.getInputStyles(n),onApprove:({orderID:e,vaultSetupToken:t,liabilityShift:i})=>{if(i===er.No||i===er.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Kr},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 nn(Xi.PaymentNotInitialized);try{this.stylizeInputContainers(i),lc(i)&&(yield this.renderFields(i)),uc(i)&&(yield this.renderVaultedFields(i))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return uc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>hc(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:()=>hc(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,i,n,r;return hc(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===(i=e.cardExpiry)||void 0===i?void 0:i.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(n=e.cardName)||void 0===n?void 0:n.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,i,n;return hc(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===(i=e.cardExpiryVerification)||void 0===i?void 0:i.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(n=e.cardNumberVerification)||void 0===n?void 0:n.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(_d(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(gd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return hc(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i={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(i)}catch(e){throw new Kr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return hc(this,void 0,void 0,function*(){const i=this.getCardFieldsOrThrow(),n=yield i.getState().then(e=>e),r=this.getValidityData(n);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 ao(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const i=Object.keys(t);return{isValid:i.every(e=>{var i;return null===(i=t[e])||void 0===i?void 0:i.isValid}),errors:i.reduce((e,i)=>{var n;const r=this.mapFieldType(i);return Object.assign(Object.assign({},e),{[r]:(null===(n=t[i])||void 0===n?void 0:n.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case cc.CardCode:case cc.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case cc.CardNumber:case cc.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case cc.CardExpiry:case cc.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(i=>{var n,r;t[i]=[{message:(null===(r=null===(n=e[i])||void 0===n?void 0:n[0])||void 0===r?void 0:r.message)||"",type:i}]}),t}mapFieldType(e){switch(e){case"name":return cc.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?cc.CardNumber:cc.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?cc.CardExpiry:cc.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?cc.CardCode:cc.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new nn(Xi.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,i,n;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.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 i;null===(i=null==e?void 0:e.onValidate)||void 0===i||i.call(e,this.getValidityData(t))}onFocusHandler(e,t){var i;null===(i=null==e?void 0:e.onFocus)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var i;null===(i=null==e?void 0:e.onBlur)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var i;null===(i=null==e?void 0:e.onEnter)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,i;const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(e),o=n.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===(i=null==r?void 0:r.initializationData)||void 0===i?void 0:i.isBigCommercePaymentsAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return hc(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getPaymentMethodOrThrow(e),{initializationData:r}=n;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.bigCommercePaymentsSdk.getPayPalFastlaneSdk(n,i.currency.code,i.id);yield this.bigCommercePaymentsFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const mc=Rt(e=>new pc(e,vr(e),zr(),Rr()),[{id:"bigcommerce_payments_creditcards"}]);var yc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class gc{constructor(e,t,i,n,r=3e3,o=3e5){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.bigCommercePaymentsSdkHelper=i,this.loadingIndicator=n,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=V,this.isPollingEnabled=!1}initialize(e){return yc(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,bigcommerce_payments_apms:n}=e;if(this.bigCommercePaymentsAlternativeMethods=n,!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(i,t),{orderId:a,shouldRenderFields:s}=o.initializationData||{},d=r.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=Wt(d,"PAYPAL-5624.bcp_ideal_polling"),a?this.orderId=a:(this.paypalApms=yield this.bigCommercePaymentsSdkHelper.getPayPalApmsSdk(o,r.getCartOrThrow().currency.code),this.loadingIndicatorContainer=n.container.split("#")[1],this.renderButton(i,t,n),s&&this.renderFields(i,n))})}execute(e,t){return yc(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{methodId:r,gatewayId:o}=i;if(!this.orderId)throw new Jr;this.isPollingEnabled&&"ideal"===r&&(yield new Promise((e,t)=>{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)||(yield this.paymentIntegrationService.submitOrder(n,t)),yield this.bigCommercePaymentsIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new vd)}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,i,n){return yc(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.bigCommercePaymentsIntegrationService.getOrderStatus(n),o=r===ar.Approved,a=r===ar.PollingError;if(o)return this.deInitializePollingMechanism(),t();if(a)return i();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,bigCommercePaymentsAlternativeMethods:this.bigCommercePaymentsAlternativeMethods}),this.handleError(new rc)}catch(e){i()}})}deInitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deInitializePollingMechanism()}reinitializeStrategy(e){return yc(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,i){const n=this.getPaypalAmpsSdkOrThrow(),r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t),{buttonStyle:o}=r.initializationData||{},{container:a,onError:s,onRenderButton:d,submitForm:c}=i,l={fundingSource:e,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o),onInit:(e,t)=>i.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,i),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deInitializePollingMechanism()},onError:e=>{this.deInitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>yc(this,void 0,void 0,function*(){return i.onValidate(t.resolve,t.reject)})};this.bigCommercePaymentsButton=n.Buttons(l),this.bigCommercePaymentsButton.isEligible()&&(d&&"function"==typeof d&&d(),this.bigCommercePaymentsButton.render(a))}onCreateOrder(e,t,i){return yc(this,void 0,void 0,function*(){const{onValidate:n}=i;yield n(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),V);const r=yield this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms");if(this.isNonInstantPaymentMethod(e)){const i={useStoreCredit:!1},n={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(i,n),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 i=this.getPaypalAmpsSdkOrThrow(),n=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=n.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new gn('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}}};i.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in or}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new pn;return this.paypalApms}}const vc=Rt(e=>new gc(e,vr(e),zr(),new td({containerStyles:Hd})),[{gateway:"bigcommerce_payments_apms"}]);class fc{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){const{gatewayId:t,methodId:i,bigcommerce_payments_apms:n}=e;if(this.bigCommercePaymentsAlternativeMethods=n,!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');return Promise.resolve()}execute(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{methodId:r,gatewayId:o}=i;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(n,t),yield this.paymentIntegrationService.submitPayment({methodId:r,gatewayId:o,paymentData:e})}catch(e){if(function(e){var t,i;return ca(e)&&(null===(i=null===(t=e.body)||void 0===t?void 0:t.additional_action_required)||void 0===i?void 0:i.data.redirect_url)}(e)){const t=e.body.additional_action_required.data.redirect_url;return new Promise((e,i)=>{window.location.replace(t),i()})}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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}deinitialize(){return Promise.resolve()}handleError(e){const{onError:t}=this.bigCommercePaymentsAlternativeMethods||{};t&&"function"==typeof t&&t(e)}}const Sc=Rt(e=>new fc(e,vr(e)),[{gateway:"bigcommerce_payments_apms",id:"klarna"},{gateway:"bigcommerce_payments_apms",id:"afterpay"}]);var wc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ic{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.loadingIndicator=i}initialize(e){var t,i;return wc(this,void 0,void 0,function*(){const{methodId:n,bigcommerce_payments_venmo:r}=e||{};if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);(null===(t=o.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(i=o.initializationData)||void 0===i?void 0:i.orderId:(yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n),this.loadingIndicatorContainer=r.container.split("#")[1],this.renderButton(n,r))})}execute(e,t){return wc(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);if(!this.orderId)throw new Jr;yield this.paymentIntegrationService.submitOrder(n,t),yield this.bigCommercePaymentsIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){const i=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=n.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u={fundingSource:i.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=i.Buttons(u),!this.paypalButton.isEligible())throw new vn("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 wc(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;yield t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}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 _c=Rt(e=>new Ic(e,vr(e),new td({styles:{backgroundColor:"black"}})),[{id:"bigcommerce_payments_venmo"}]);class Cc{initialize(e){this._blueSnapSdk=e}initialize3ds(e,t){return i=this,n=void 0,o=function*(){const i=this._getBlueSnapSdk();return new Promise((n,r)=>{i.threeDsPaymentsSetup(e,e=>"1"===e.code?n(e.threeDSecure.threeDSecureReferenceId):r(new Kr)),i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_getBlueSnapSdk(){return tn(this._blueSnapSdk,()=>new nn(Xi.PaymentNotInitialized))}}function bc(e){return cc.CardNumber in e}function Pc(e){return cc.CardCodeVerification in e||cc.CardNumberVerification in e}var Oc,Ec,Ac,Tc,kc,Dc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Mc{constructor(e,t,i,n){this._scriptLoader=e,this._paymentIntegrationService=t,this._blueSnapDirectHostedForm=i,this._blueSnapDirect3ds=n}initialize(e){return Dc(this,void 0,void 0,function*(){const{methodId:t,gatewayId:i,creditCard:n}=e;if(!i||!n)throw new gn;const r=yield this._paymentIntegrationService.loadPaymentMethod(i,{params:{method:t,bigpayToken:n.bigpayToken}}),{config:{testMode:o,is3dsEnabled:a},clientToken:s}=r.getPaymentMethodOrThrow(t,i);this._blueSnapSdk=yield this._scriptLoader.load(o),this._paymentFieldsToken=s,this._shouldUseHostedFields=bc(n.form.fields)||Pc(n.form.fields)&&!!n.form.fields.cardNumberVerification,this._shouldUseHostedFields&&(this._blueSnapDirectHostedForm.initialize(this._blueSnapSdk,n.form.fields),yield this._blueSnapDirectHostedForm.attach(this._getPaymentFieldsToken(),n,a))})}execute(e){return Dc(this,void 0,void 0,function*(){if(!e.payment)throw new oo(["payment"]);if(!this._blueSnapSdk)throw new oo(["payment"]);const{paymentData:t}=e.payment,{shouldSaveInstrument:i,shouldSetAsDefaultInstrument:n}=_d(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,!(_d(t)&&gd(t))):void 0;if(yield this._paymentIntegrationService.submitOrder(),_d(t)&&gd(t)&&this._paymentFieldsToken&&t.instrumentId){if(a){this._blueSnapDirect3ds.initialize(this._blueSnapSdk);const{last4:e,brand:i}=this._paymentIntegrationService.getState().getCardInstrumentOrThrow(t.instrumentId),n=Object.assign({last4Digits:e,ccType:i.toUpperCase()},this._getBlueSnapDirectThreeDSecureData());o=yield this._blueSnapDirect3ds.initialize3ds(this._paymentFieldsToken,n)}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:!!n})}))}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:i,set_as_default_stored_instrument:n}}}))})}finalize(){return Promise.reject(new vd)}deinitialize(){return this._shouldUseHostedFields&&this._blueSnapDirectHostedForm.detach(),Promise.resolve()}_getBlueSnapDirectThreeDSecureData(){var e;const{getBillingAddress:t,getShippingAddress:i,getCustomer:n,getCheckoutOrThrow:r,getCartOrThrow:o}=this._paymentIntegrationService.getState(),a=t(),s=i(),d=(null===(e=n())||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 tn(this._paymentFieldsToken,()=>new Qi(Zi.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"}(Oc||(Oc={})),function(e){e.ON_BLUR="onBlur",e.ON_SUBMIT="onSubmit"}(Ec||(Ec={})),function(e){e.EMPTY="empty",e.INVALID="invalid",e.THREE_DS_NOT_ENABLED="3D Secure is not enabled"}(Ac||(Ac={})),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"}(Tc||(Tc={})),function(e){e.CardCode="cvv",e.CardExpiry="exp",e.CardName="noc",e.CardNumber="ccn"}(kc||(kc={}));const zc={[kc.CardNumber]:cc.CardNumber,[kc.CardExpiry]:cc.CardExpiry,[kc.CardName]:cc.CardName,[kc.CardCode]:cc.CardCode},Nc={empty:{[cc.CardNumber]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[cc.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number is required",type:"required"},[cc.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date is required",type:"required"},[cc.CardCode]:{fieldType:"cardCode",message:"CVV is required",type:"required"},[cc.CardName]:{fieldType:"cardName",message:"Full name is required",type:"required"}},invalid:{[cc.CardNumber]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[cc.CardNumberVerification]:{fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},[cc.CardExpiry]:{fieldType:"cardExpiry",message:"Expiration date must be a valid future date in MM / YY format",type:"invalid_card_expiry"},[cc.CardCode]:{fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},[cc.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&&(bc(t)?this._hostedInputValidator.initialize():Pc(t)&&t.cardNumberVerification&&this._hostedInputValidator.initializeValidationFields())}attach(e,t,i){var n,r,o,a,s=t.form,{fields:d}=s,c=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(s,["fields"]);return void 0===i&&(i=!1),n=this,r=void 0,a=function*(){const t=this._getBlueSnapSdk();if(!bc(d)&&!Pc(d))throw new gn("Field options must be of type HostedCardFieldOptionsMap");return this._onValidate=c.onValidate,bc(d)&&this._setCustomBlueSnapAttributes(d),Pc(d)&&this._setCustomStoredCardsBlueSnapAttributes(d),new Promise(n=>{const r=this._getHostedPaymentFieldsOptions(e,d,c,n,i);t.hostedPaymentFieldsCreate(r),bc(d)&&this._nameOnCardInput.attach(r,d.cardName.accessibilityLabel,d.cardName.placeholder)})},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,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,i])=>Object.assign(Object.assign({},e),{[t]:i.map(({message:e,type:t})=>({message:e,type:t}))}),{});throw new ao(e)}return this}submit(e,t=!1){return new Promise((i,n)=>this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(e=>this._isBlueSnapDirectCallbackError(e)?n(new Kr(e.statusCode===Tc.THREE_DS_AUTH_FAILED?e.error[0].errorDescription:`Submission failed with status: ${e.statusCode} and errors: ${JSON.stringify(e.error)}`)):i(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:i,onBlur:n,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(i),onBlur:this._usetUiEventCallback(n),onError:this._handleError(r),onType:(e,t)=>null==o?void 0:o({cardType:Oc[t]}),onEnter:this._usetUiEventCallback(a),onValid:e=>null==r?void 0:r(this._hostedInputValidator.validate({tagId:e}))}},bc(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:i}){return Object.entries(Object.assign(Object.assign(Object.assign({},e&&{input:e}),t&&{".invalid":t}),i&&{":focus":i})).reduce((e,[t,i])=>Object.assign(Object.assign({},e),{[t]:Object.entries(i).reduce((e,[t,i])=>Object.assign(Object.assign({},e),{[x(t)]:i}),{})}),{})}_handleError(e){return(t,i,n,r)=>{if(i===Tc.INVALID_OR_EMPTY&&t&&function(e){return void 0!==e&&[Ac.EMPTY,Ac.INVALID].includes(e)}(n))return null==e?void 0:e(this._hostedInputValidator.validate({tagId:t,errorDescription:n}));throw new Kr(`An unexpected error has occurred: ${JSON.stringify({tagId:t,errorCode:i,errorDescription:n,eventOrigin:r})}`)}}_usetUiEventCallback(e){return t=>{e&&e({fieldType:zc[t]})}}_getBlueSnapSdk(){return tn(this._blueSnapSdk,()=>new nn(Xi.PaymentNotInitialized))}_setCustomBlueSnapAttributes(e){const{cardNumber:t,cardExpiry:i,cardCode:n,cardName:r}=e,o=document.getElementById(t.containerId),a=document.getElementById(i.containerId),s=n&&document.getElementById(n.containerId),d=document.getElementById(r.containerId);if(!(o&&a&&s&&d))throw new gn("Unable to create hosted payment fields to invalid HTML container elements.");o.dataset.bluesnap=kc.CardNumber,a.dataset.bluesnap=kc.CardExpiry,s.dataset.bluesnap=kc.CardCode,d.dataset.bluesnap=kc.CardName}_setCustomStoredCardsBlueSnapAttributes(e){const{cardNumberVerification:t,cardCodeVerification:i}=e,n=t&&document.getElementById(t.containerId),r=i&&document.getElementById(i.containerId);(n||r)&&(n&&(n.dataset.bluesnap=kc.CardNumber),r&&(r.dataset.bluesnap=kc.CardCode))}}class Fc{constructor(){this._errors={}}initialize(){this._errors={cardNumber:[Nc.empty.cardNumber],cardExpiry:[Nc.empty.cardExpiry],cardCode:[Nc.empty.cardCode],cardName:[Nc.empty.cardName]}}initializeValidationFields(){this._errors={cardNumberVerification:[Nc.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 i=this._errors.cardNumberVerification?cc.CardNumberVerification:zc[e];this._errors[i]=t?[Nc[t][i]]:[]}}class Rc{attach({style:e,onFieldEventHandler:{onFocus:t,onBlur:i,onValid:n,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(i,n,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(kc.CardName)}}_handleBlur(e,t,i){return({target:n})=>{var r,o;null==e||e(kc.CardName),n instanceof HTMLInputElement&&(/\w{1,200}/.test(n.value)?(this._applyStyles(null===(r=this._style)||void 0===r?void 0:r.input),null==t||t(kc.CardName)):(this._applyStyles(null===(o=this._style)||void 0===o?void 0:o[".invalid"]),null==i||i(kc.CardName,Tc.INVALID_OR_EMPTY,Ac.EMPTY,Ec.ON_BLUR)))}}_handleEnter(e){return()=>null==e?void 0:e(kc.CardName)}_applyStyles(e={}){const t={color:e.color,fontFamily:e["font-family"],fontSize:e["font-size"],fontWeight:e["font-weight"]},i=Object.keys(t);i.every(e=>["color","fontFamily","fontSize","fontWeight"].includes(e))&&i.forEach(e=>{t[e]&&(this._getInput().style[e]=t[e]||"")})}_configureInput(){this._getInput().autocomplete="cc-name",this._getInput().id=kc.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 tn(this._input,()=>new nn(Xi.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 Lc;!function(e){e.PRODUCTION="https://pay.bluesnap.com/web-sdk/5/bluesnap.js",e.SANDBOX="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"}(Lc||(Lc={}));class Bc{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e=!1){return t=this,i=void 0,r=function*(){if(this._window.bluesnap)return this._window.bluesnap;if(yield this._scriptLoader.loadScript(e?Lc.SANDBOX:Lc.PRODUCTION),!this._window.bluesnap)throw new pn;return this._window.bluesnap},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}const jc=Rt(e=>new Mc(new Bc(a()),e,new xc(new Rc,new Fc),new Cc),[{id:"credit_card",gateway:"bluesnapdirect"}]);class Uc{constructor(e){this._paymentIntegrationService=e}execute(e){return t=this,i=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 i=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();i=`${i}&${e}`}return new Promise(()=>window.location.replace(i))}return Promise.reject(e)}},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}initialize(){return Promise.resolve()}finalize(){return Promise.reject(new vd)}deinitialize(){return Promise.resolve()}_formatePaymentPayload({payment:e}){if(!e)throw new oo(["payment"]);return e.paymentData&&gd(e.paymentData)&&_d(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}}}):(i=e.paymentData,Boolean("object"==typeof i&&null!==i&&"iban"in i&&"firstName"in i&&"lastName"in i&&"shopperPermission"in i)?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,i}_isBlueSnapDirectRedirectResponse(e){var t;if("object"!=typeof e||null===e)return!1;const i=e;if(!i.body)return!1;const n=i.body;return"additional_action_required"===n.status&&!!(null===(t=n.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}}const qc=Rt(e=>new Uc(e),[{gateway:"bluesnapdirect"}]);var Vc;!function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(Vc||(Vc={}));const Gc=Vc;var Hc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class $c{constructor(e){this._paymentIntegrationService=e}execute(e,t){return Hc(this,void 0,void 0,function*(){const{payment:i}=e;if(!i)throw new oo(["payment"]);if(!this._initializeOptions)throw new nn(Xi.PaymentNotInitialized);const{onLoad:n,style:r}=this._initializeOptions,o=this._createIframe("bluesnapv2_hosted_payment_page",r),a=new Pi(new Promise(V));n(o,()=>a.cancel(new Vn)),yield this._paymentIntegrationService.submitOrder(e,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:i.methodId,gatewayId:i.gatewayId,shouldSaveInstrument:!1,target:o.name,promise:a.promise})})}finalize(e){return Hc(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),i=t.getOrder(),n=t.getPaymentStatus();if(!i||n!==Gc.ACKNOWLEDGE&&n!==Gc.FINALIZE)return Promise.reject(new vd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(e){return Hc(this,void 0,void 0,function*(){this._initializeOptions=e&&e.bluesnapv2,yield Promise.resolve()})}deinitialize(){return Promise.resolve()}_createIframe(e,t){const i=document.createElement("iframe");if(i.setAttribute("sandbox","allow-top-navigation allow-scripts allow-forms allow-same-origin"),i.name=e,t){const{border:e,height:n,width:r}=t;i.style.border=null!=e?e:"",i.style.height=null!=n?n:"",i.style.width=null!=r?r:""}return i}}const Wc=Rt(e=>new $c(e),[{gateway:"bluesnapv2"}]);class Yc{constructor(e){this.storage=e}saveExtraItemsData(e,t){const i=[...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(i)),i}catch(e){return{}}}readExtraItemsData(e){try{const t=this.storage.getItem(this.getStorageKey(e));if(!t)return null;const i=JSON.parse(t);return function(e){if(!D(e))return!1;const t=Object.values(e).some(e=>!D(e)||!("brand"in e)||!("category"in e));return Boolean(!t)}(i)?i:null}catch(e){return null}}clearExtraItemData(e){try{this.storage.removeItem(this.getStorageKey(e))}catch(e){}}getStorageKey(e){return e?`ORDER_ITEMS_${e}`:""}}function Kc(e){return Boolean(e.hasOwnProperty("analytics"))}function Jc(e){return"object"==typeof e&&null!==e&&"shouldCreateAccount"in e}class Zc extends Ji{constructor(e){super(),this.errorCode=e,this.name="BoltPaymentsFieldError",this.type="bolt_payments_field_error",this.body={errors:[Zc.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 Xc=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Qc{constructor(e,t,i){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.analyticsExtraItemsManager=i,this.useBoltClient=!1,this.useBoltEmbedded=!1}initialize(e){return Xc(this,void 0,void 0,function*(){const{bolt:t,methodId:i}=e,{containerId:n,onPaymentSelect:r,useBigCommerceCheckout:o}=t||{};if(!i)throw new gn('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 Qi(Zi.MissingPaymentMethod);if(this.boltClient=yield this.boltScriptLoader.loadBoltClient(c,h,l),this.useBoltClient=!u,this.useBoltEmbedded=!!u,this.useBoltEmbedded){if(!n)throw new gn('Unable to initialize payment because "options.bolt.containerId" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.bolt.onPaymentSelect" argument is not provided.');this.boltEmbedded=yield this.boltScriptLoader.loadBoltEmbedded(c,h,l),this.mountBoltEmbeddedField(n),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 vd)}execute(e,t){return Xc(this,void 0,void 0,function*(){this.setExtraItemsForAnalytics();const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{methodId:r,paymentData:o}=i||{};let a;if(!e.payment)throw new oo(["payment"]);if(!r)throw new Qi(Zi.MissingPaymentMethod);if(!o||!function(e){return Boolean(D(e)&&("shouldSaveInstrument"in e||"nonce"in e||Jc(e)))}(o))throw new Qi(Zi.MissingPayment);yield this.paymentIntegrationService.submitOrder(n,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,i){return Xc(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadPaymentMethod(e,i);const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(e).clientToken,{isStoreCreditApplied:o}=n.getCheckoutOrThrow(),{shouldSaveInstrument:a}=t,s=this.getBoltClientOrThrow();if(yield this.paymentIntegrationService.applyStoreCredit(o),!r)throw new Qi(Zi.MissingPaymentMethod);const d=yield new Promise((e,t)=>{const i={success:(i,n)=>{i.reference?e(i):t(new Kr("Unable to proceed because transaction reference is unavailable. Please try again later.")),n()},close:()=>{t(new Vn)}};s.configure({orderToken:r},{},i).open()});return{methodId:e,paymentData:{nonce:d.reference,shouldSaveInstrument:a}}})}getBoltEmbeddedPaymentPayload(e,t){var i;return Xc(this,void 0,void 0,function*(){if(!Jc(t))throw new Qi(Zi.MissingPayment);const n=this.validateTokenizeResultOrThrow(yield null===(i=this.embeddedField)||void 0===i?void 0:i.tokenize());return{methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:n.token,last_four_digits:n.last4,iin:n.bin,expiration_month:+n.expiration.split("-")[1],expiration_year:+n.expiration.split("-")[0]},provider_data:{create_account:!!t.shouldCreateAccount,embedded_checkout:!0}}}}})}getBoltFullCheckoutPaymentPayload(e,t){return Xc(this,void 0,void 0,function*(){yield this.setBoltOrderId();const i=this.getBoltClientOrThrow(),n=yield i.getTransactionReference();if(!n)throw new Jr;return{methodId:e,paymentData:Object.assign(Object.assign({},t),{nonce:n})}})}getBoltClientOrThrow(){if(!this.boltClient)throw new nn(Xi.PaymentNotInitialized);return this.boltClient}getBoltEmbeddedOrThrow(){if(!this.boltEmbedded)throw new nn(Xi.PaymentNotInitialized);return this.boltEmbedded}hasBoltAccount(){return Xc(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),t=e.getCustomer(),i=e.getBillingAddress(),n=(null==t?void 0:t.email)||(null==i?void 0:i.email)||"",r=this.getBoltClientOrThrow();try{return yield r.hasBoltAccount(n)}catch(e){throw new Jr}})}setBoltOrderId(){return Xc(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 Jr}})}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 Jr;if(e instanceof Error)throw new Zc(e.message);const{token:t,last4:i,bin:n,expiration:r}=e,o=+i,a=+n,s=+`${r}`.split("-")[1],d=+`${r}`.split("-")[0];if(!t||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(s)||Number.isNaN(d))throw new oo;return e}setExtraItemsForAnalytics(){const e=this.paymentIntegrationService.getState(),t=e.getStoreConfigOrThrow(),i=e.getCartOrThrow();if(t.checkoutSettings.isAnalyticsEnabled&&Kc(window)){const{id:e,lineItems:t}=i;this.analyticsExtraItemsManager.saveExtraItemsData(e,t)}}}const el=Rt(e=>new Qc(e,new no(a()),new Yc(Te)),[{id:"bolt"}]);function tl(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var il=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class nl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeSdk=t}initialize(e){return il(this,void 0,void 0,function*(){const{methodId:t,braintreeach:i}=e||{};if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');this.getMandateText=null==i?void 0:i.getMandateText,yield this.paymentIntegrationService.loadPaymentMethod(t);const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{clientToken:r,initializationData:o}=n;if(!r||!o)throw new Qi(Zi.MissingPaymentMethod);this.braintreeSdk.initialize(r);try{this.usBankAccount=yield this.braintreeSdk.getUsBankAccount()}catch(e){this.handleBraintreeError(e)}})}execute(e,t){return il(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const r=gd(i.paymentData||{}),o=r?yield this.tokenizePaymentForVaultedInstrument(i):yield this.tokenizePayment(i),a=r?yield this.preparePaymentDataForVaultedInstrument(o,i):yield this.preparePaymentData(o,i);yield this.paymentIntegrationService.submitOrder(n,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new vd)}deinitialize(){return il(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}tokenizePayment({paymentData:e}){return il(this,void 0,void 0,function*(){const t=this.getUsBankAccountOrThrow();if(!tl(e))throw new oo(["payment.paymentData"]);const i=gd(e)?"The data are used for stored instrument verification":"function"==typeof this.getMandateText&&this.getMandateText();if(!i)throw new gn("Unable to proceed because getMandateText is not provided or returned undefined value.");try{const{nonce:n}=yield t.tokenize({bankDetails:this.getBankDetails(e),mandateText:i});return n}catch(e){this.handleBraintreeError(e)}})}tokenizePaymentForVaultedInstrument(e){return il(this,void 0,void 0,function*(){const{methodId:t,paymentData:i={}}=e,n=this.paymentIntegrationService.getState(),{config:r}=n.getPaymentMethodOrThrow(t);if(!r.isVaultingEnabled)throw new gn("Vaulting is disabled but a vaulted instrument was being used for this transaction");return tl(i)?this.tokenizePayment(e):null})}preparePaymentData(e,t){return il(this,void 0,void 0,function*(){const{methodId:i,paymentData:n={}}=t;if(!tl(n))throw new oo(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,routingNumber:s,accountNumber:d}=n;return{methodId:i,paymentData:{deviceSessionId:r,shouldSetAsDefaultInstrument:a,shouldSaveInstrument:o,formattedPayload:{tokenized_bank_account:{issuer:s,masked_account_number:d.substr(-4),token:e}}}}})}preparePaymentDataForVaultedInstrument(e,t){return il(this,void 0,void 0,function*(){const{methodId:i,paymentData:n={}}=t;if(!gd(n)||!_d(n))throw new oo(["payment.paymentData"]);const{deviceData:r}=yield this.braintreeSdk.getDataCollectorOrThrow(),{instrumentId:o,shouldSetAsDefaultInstrument:a}=n;return{methodId:i,paymentData:Object.assign({deviceSessionId:r,instrumentId:o,shouldSetAsDefaultInstrument:a},e&&{nonce:e})}})}getBankDetails(e){const t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i=e.ownershipType.toLowerCase(),n=e.accountType.toLowerCase();return Object.assign(Object.assign({accountNumber:e.accountNumber,routingNumber:e.routingNumber,ownershipType:i},"personal"===i?{firstName:e.firstName,lastName:e.lastName}:{businessName:e.businessName}),{accountType:n,billingAddress:{streetAddress:t.address1,extendedAddress:t.address2,locality:t.city,region:t.stateOrProvinceCode,postalCode:t.postalCode}})}getUsBankAccountOrThrow(){if(!this.usBankAccount)throw new nn(Xi.PaymentNotInitialized);return this.usBankAccount}handleBraintreeError(e){if(!zn(e))throw e;throw new Kr(e.message)}}const rl=Rt(e=>new nl(e,(e=>{const t=new bn(e),i=new qn(a(),window,t);return new Ln(i)})(e)),[{id:"braintreeach"}]);class ol{constructor(e){this.paymentIntegrationService=e,this.braintreeHostWindow=window}render(e,t,i){const n=t&&document.getElementById(t);if(this.braintreeHostWindow.paypal&&n){const r=this.paymentIntegrationService.getState(),o=r.getCartOrThrow(),a=r.getBillingAddressOrThrow(),s=r.getPaymentMethodOrThrow(e);if(!s.initializationData)return;const{paypalBNPLConfiguration:d=[]}=s.initializationData,c=i===yo.PAYMENT?"checkout":i,l=d&&d.find(({id:e})=>e===c);if(!l||!l.status)return;i===yo.CART&&(n.removeAttribute("data-pp-style-logo-type"),n.removeAttribute("data-pp-style-logo-position"),n.removeAttribute("data-pp-style-text-color"),n.removeAttribute("data-pp-style-text-size")),this.braintreeHostWindow.paypal.Messages({amount:o.cartAmount,buyerCountry:a.countryCode,placement:i,style:this.getPaypalMessagesStylesFromBNPLConfig(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 al{constructor(e){const{element:t,closeElement:i,mainElement:n}=this._createElements(e);this._element=t,this._closeElement=i,this._mainElement=n}show(e){this._mainElement.parentElement||(this._registerClick(e),document.body.appendChild(this._mainElement),setTimeout(()=>this._element.style.opacity="1"))}remove(){this._mainElement.parentElement&&(this._unregisterClick&&this._unregisterClick(),this._removeAfterTransition(),setTimeout(()=>this._element.style.opacity="0"))}_createElements(e){const t=document.createElement("div"),{background:i="rgba(0, 0, 0, 0.8)",id:n="checkoutOverlay",transitionDuration:r=400,hasCloseButton:o=!1,innerHtml:a=null}=e||{};let s,d,c,l,u=t;if(n&&(t.id=n),a){const e=document.createElement("div");l=`${n}--overlayText`,e.className=l,e.appendChild(a),t.appendChild(e)}return o&&(c=`${n}--close`,s=document.createElement("div"),s.className=c,d=`${n}--layout`,u=document.createElement("div"),u.className=d,u.appendChild(t),u.appendChild(s)),u.appendChild(function(e){const{id:t,background:i,transitionDuration:n,classLayout:r,classOverlayText:o,classClose:a}=e,s=document.createElement("style"),d=r?`, .${r}`:"";return s.id=`${t}--styles`,s.type="text/css",s.innerText=`\n #${t}${d} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${t} {\n transition: opacity ${n}ms ease-out;\n background: ${i};\n opacity: 0;\n }\n `,o&&(s.innerText+=`\n #${t} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${t} .${o} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `),a&&(s.innerText+=`\n #${t} {\n opacity: 1;\n }\n .${r} .${a} {\n position: fixed;\n right: 16px;\n top: 16px;\n width: 16px;\n height: 16px;\n opacity: 0.6;\n cursor: pointer;\n z-index: 3147483647;\n }\n .${r} .${a}::after, .${r} .${a}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${r} .${a}::after {\n transform: rotate(-45deg);\n }\n .${r} .${a}::before {\n transform: rotate(45deg);\n }\n `),s}({id:n,background:i,transitionDuration:r,classLayout:d,classOverlayText: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:i}=e;this._addEventListener(this._element,t),this._addEventListener(this._closeElement,i),this._unregisterClick=()=>{this._removeEventListener(this._element,t),this._removeEventListener(this._closeElement,i),this._unregisterClick=void 0}}}_removeAfterTransition(){const e=t=>{"opacity"===t.propertyName&&(this._mainElement.parentElement&&this._mainElement.remove(),this._element.removeEventListener("transitionend",e))};this._element.addEventListener("transitionend",e)}}const sl={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"};function dl(e){return"object"==typeof e&&null!==e&&"name"in e&&"BraintreeError"===e.name}function cl(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 ll=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ul{constructor(e,t,i,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeMessages=i,this.loadingIndicator=n,this.braintreeHostWindow=window}initialize(e){return ll(this,void 0,void 0,function*(){const{braintree:t,methodId:i}=e;if(this.braintree=t,this.paymentMethod&&this.paymentMethod.nonce||(this.paymentMethod=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i)),this.paymentMethod.clientToken&&(null==t?void 0:t.bannerContainerId))return yield this.loadPaypal(),this.loadPaypalCheckoutInstance();if(this.paymentMethod.clientToken)return this.loadPaypal();const n=yield this.paymentIntegrationService.loadPaymentMethod(i);if(this.paymentMethod=n.getPaymentMethodOrThrow(i),null==t?void 0:t.bannerContainerId)return this.loadPaypalCheckoutInstance();if(!this.paymentMethod.clientToken)throw new Qi(Zi.MissingPaymentMethod);return this.loadPaypal()})}execute(e,t){var i;return ll(this,void 0,void 0,function*(){const{payment:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{onError:o}=this.braintree||{};if(!n)throw new oo(["payment"]);try{const e=yield this.preparePaymentData(n,r.useStoreCredit);yield this.paymentIntegrationService.submitOrder(r,t),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.isProviderError(e)&&(yield this.loadPaypal(),null===(i=this.paypalButtonRender)||void 0===i||i.close(),yield this.loadPaypalCheckoutInstance(),yield new Promise((e,t)=>{o&&"function"==typeof o&&o(new Error("INSTRUMENT_DECLINED")),t()})),this.handleError(e)}})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;return this.braintreeTokenizePayload=void 0,null===(e=this.paypalButtonRender)||void 0===e||e.close(),this.braintreeIntegrationService.teardown()}preparePaymentData(e,t){var i;return ll(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),r=n.getOutstandingBalance(t),o=n.getStoreConfig();if(!r)throw new Qi(Zi.MissingCheckout);if(!o)throw new Qi(Zi.MissingCheckoutConfig);if(!this.paymentMethod)throw new nn(Xi.PaymentNotInitialized);const{currency:a,storeProfile:{storeLanguage:s}}=o,{nonce:d,config:{isVaultingEnabled:c}}=this.paymentMethod,{methodId:l,paymentData:u={}}=e,h=(null===(i=this.braintreeTokenizePayload)||void 0===i?void 0:i.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(gd(u)||(p=u,Boolean(p.instrumentId)&&!Object.prototype.hasOwnProperty.call(p,"ccNumber")&&!Object.prototype.hasOwnProperty.call(p,"ccCvv"))){if(!c)throw new gn("Vaulting is disabled but a vaulted instrument was being used for this transaction");return Promise.resolve(e)}var p;if(!_d(u))throw new Qi(Zi.MissingPayment);const{shouldSaveInstrument:m,shouldSetAsDefaultInstrument:y}=u;if(m&&!c)throw new gn("Vaulting is disabled but shouldSaveInstrument is set to true");const g=n.getShippingAddress(),v=g?cl(g):void 0;return Promise.all([this.braintreeIntegrationService.paypal({amount:r,locale:s,currency:a.code,offerCredit:"braintreepaypalcredit"===this.paymentMethod.id,shippingAddressOverride:v,shouldSaveInstrument:m||!1,shippingAddressEditable:!1}),this.braintreeIntegrationService.getSessionId()]).then(([{nonce:t,details:i}={},n])=>Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(t,i&&i.email,n,m,y)}))})}formattedPayload(e,t,i,n,r){return{formattedPayload:{vault_payment_instrument:n||null,set_as_default_stored_instrument:r||null,device_info:i||null,paypal_account:{token:e,email:t||null}}}}loadPaypalCheckoutInstance(){return ll(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t,id:i}=this.paymentMethod||{};if(!e)throw new Qi(Zi.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e);const n={currency:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,intent:null==t?void 0:t.intent,isCreditEnabled:null==t?void 0:t.isCreditEnabled},r="braintreepaypalcredit"===i||!(null==t?void 0:t.isCreditEnabled);yield this.braintreeIntegrationService.getPaypalCheckout(n,e=>{var t;r&&i&&(null===(t=this.braintree)||void 0===t?void 0:t.bannerContainerId)&&this.renderPayPalMessages(i,this.braintree.bannerContainerId),this.renderPayPalButton(e)},this.handleError)}catch(e){this.handleError(e)}})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,yo.PAYMENT)}renderPayPalButton(e){const{onPaymentError:t,submitForm:i,onRenderButton:n,containerId:r,onError:o}=this.braintree||{};if(!r)return;if(!this.paymentMethod)throw new nn(Xi.PaymentNotInitialized);this.loadingIndicatorContainer=r.split("#")[1];const{id:a,config:{testMode:s}}=this.paymentMethod,{paypal:d}=this.braintreeHostWindow,c=null==d?void 0:d.FUNDING.PAYPAL;d&&c?(this.paypalButtonRender=d.Buttons({env:s?"sandbox":"production",commit:!1,fundingSource:c,onClick:()=>{this.toggleLoadingIndicator(!0)},createOrder:()=>this.setupPayment(e,a,t),onApprove:t=>ll(this,void 0,void 0,function*(){this.braintreeTokenizePayload=yield this.tokenizePaymentOrThrow(t,e),i&&"function"==typeof i&&i()}),onCancel:()=>{this.toggleLoadingIndicator(!1)},onError:e=>{this.toggleLoadingIndicator(!1),null==o||o(e)}}),n&&"function"==typeof n&&n(),this.paypalButtonRender.isEligible()&&this.paypalButtonRender.render(`${r}`)):this.removeElement(r.split("#")[1])}setupPayment(e,t,i){return ll(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState();try{const i=n.getCustomer(),r=n.getPaymentMethodOrThrow(t),o=n.getCheckoutOrThrow().outstandingBalance,a=n.getStoreConfigOrThrow().currency.code,s=n.getShippingAddress()||(null==i?void 0:i.addresses[0]),d=s?cl(s):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:d,amount:o,currency:a,offerCredit:!1,intent:r.initializationData.intent})}catch(e){throw i&&(dl(e)||e instanceof Ji)&&i(e),e}})}tokenizePaymentOrThrow(e,t,i){return ll(this,void 0,void 0,function*(){try{return yield t.tokenizePayment(e)}catch(e){throw i&&(dl(e)||e instanceof Ji)&&i(e),e}})}loadPaypal(){return ll(this,void 0,void 0,function*(){const{clientToken:e,initializationData:t}=this.paymentMethod||{};if(!e||!t)throw new Qi(Zi.MissingPaymentMethod);try{this.braintreeIntegrationService.initialize(e),yield this.braintreeIntegrationService.getPaypal()}catch(e){this.handleError(e)}return Promise.resolve()})}handleError(e){if(!dl(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Vn(e.message);throw new Kr(e.message)}isProviderError(e){var t,i,n;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"2046"===(null===(n=null===(i=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===i?void 0:i.provider_error)||void 0===n?void 0:n.code)}removeElement(e){const t=e&&document.getElementById(e);t&&t.remove()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const hl=Rt(e=>{const t=window,i=new al,n=new bn(e),r=new vo(new qn(a(),t,n),t,i),o=new ol(e);return new ul(e,r,o,new td({containerStyles:sl}))},[{id:"braintreepaypal"},{id:"braintreepaypalcredit"}]);class pl{constructor(e){this.requestSender=e}getOrderStatus(e="braintreelocalmethods",t){return i=this,n=void 0,o=function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body},new((r=void 0)||(r=Promise))(function(e,t){function a(e){try{d(o.next(e))}catch(e){t(e)}}function s(e){try{d(o.throw(e))}catch(e){t(e)}}function d(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}var ml=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class yl{constructor(e,t,i,n,r=3e3,o=3e5){this.paymentIntegrationService=e,this.braintreeSdk=t,this.braintreeRequestSender=i,this.loadingIndicator=n,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.isLPMsUpdateExperimentEnabled=!1,this.pollingTimer=0,this.stopPolling=V,this.isPollingEnabled=!1}initialize(e){return ml(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,braintreelocalmethods:n}=e;if(this.gatewayId=t,!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');this.braintreelocalmethods=n,this.loadingIndicatorContainer=n.container.split("#")[1],yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(t),{clientToken:a,config:s,initializationData:d}=o,c=r.getStoreConfigOrThrow().checkoutSettings.features;if(this.isPollingEnabled=Wt(c,"PAYPAL-5258.braintree_local_methods_polling"),this.isLPMsUpdateExperimentEnabled=Wt(c,"PAYPAL-4853.add_new_payment_flow_for_braintree_lpms"),!a||!d||!s.merchantId)throw new Qi(Zi.MissingPaymentMethod);try{this.braintreeSdk.initialize(a),this.isNonInstantPaymentMethod(i)||(this.braintreeLocalPayment=yield this.braintreeSdk.getBraintreeLocalPayment(s.merchantId))}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new vd)}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:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{methodId:r}=i;this.toggleLoadingIndicator(!0),this.isNonInstantPaymentMethod(r)?yield this.executeWithNotInstantLPM(r):yield this.executeWithInstantLPM(r,n,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,i)=>{window.location.replace(t),this.toggleLoadingIndicator(!1),i()})}return this.handleError(e),Promise.reject(e)}})}executeWithInstantLPM(e,t,i){return ml(this,void 0,void 0,function*(){if(!this.braintreeLocalPayment)throw new Jr;yield new Promise((n,r)=>{var o;null===(o=this.braintreeLocalPayment)||void 0===o||o.startPayment(this.getInstantLPMConfig(e,t,i),this.getInstantLPMCallback(n,r,e,t,i))})})}getLPMsBasicPaymentData(){return ml(this,void 0,void 0,function*(){const{deviceData:e}=yield this.braintreeSdk.getDataCollectorOrThrow();return{deviceSessionId:e}})}getInstantLPMConfig(e,t,i){const n=this.paymentIntegrationService.getState(),r=n.getCartOrThrow(),o=n.getBillingAddressOrThrow(),{firstName:a,lastName:s,countryCode:d}=o,{currency:c,email:l,lineItems:u}=r,h=u.physicalItems.length>0,p=n.getCheckoutOrThrow().outstandingBalance,m=n.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:(n,r)=>ml(this,void 0,void 0,function*(){if(!this.isLPMsUpdateExperimentEnabled)return this.orderId=n.paymentId,void r();const o=yield this.getLPMsBasicPaymentData(),a=Object.assign(Object.assign({},o),{formattedPayload:{method:e,[`${e}_account`]:{order_id:n.paymentId}}});try{yield this.paymentIntegrationService.submitOrder(t,i),yield this.paymentIntegrationService.submitPayment({methodId:e,paymentData:a})}catch(t){if(this.isBraintreeOrderSavedResponse(t)&&t.body.additional_action_required.data.order_id_saved_successfully)return r(),this.isPollingEnabled?new Promise((t,i)=>{this.initializePollingMechanism(e,t,i,this.gatewayId)}):void 0;throw t}})}}getInstantLPMCallback(e,t,i,n,r){const o=this.paymentIntegrationService.getState().getCartOrThrow();return(a,s)=>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 Jr));const d=yield this.getLPMsBasicPaymentData(),c=Object.assign(Object.assign({},d),{formattedPayload:{method:i,[`${i}_account`]:Object.assign({email:o.email,token:s.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId})}});try{return this.isLPMsUpdateExperimentEnabled||(yield this.paymentIntegrationService.submitOrder(n,r)),yield this.paymentIntegrationService.submitPayment({methodId:i,paymentData: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 An}isBraintreeRedirectError(e){var t;if("object"!=typeof e||null===e)return!1;const{body:i}=e;return!!i&&!!(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.redirect_url)}isBraintreeOrderSavedResponse(e){var t;if("object"!=typeof e||null===e)return!1;const{body:i}=e;return!!i&&(null===(t=i.additional_action_required)||void 0===t?void 0:t.data.hasOwnProperty("order_id_saved_successfully"))}initializePollingMechanism(e,t,i,n){return ml(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.braintreeRequestSender.getOrderStatus(n,{params:{useMetadata:!1}}),o=r.status===En.Pending,a=r.status===En.Completed,s=r.status===En.Failed;if(a)return this.deinitializePollingMechanism(),t();if(s)return i();if(!a&&o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,braintreelocalmethods:this.braintreelocalmethods}),this.handleError(new rc)}catch(e){i()}})}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 gl=Rt(e=>{const t=window,n=new bn(e),r=new Ln(new qn(a(),t,n)),o=i(),s=new pl(o);return new yl(e,r,s,new td({styles:{backgroundColor:"black"}}))},[{gateway:"braintreelocalmethods"}]);function vl(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var fl=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Sl{constructor(e,t,i){this.paymentIntegrationService=e,this.braintreeFastlaneUtils=t,this.braintreeSdk=i}initialize(e){var t;return fl(this,void 0,void 0,function*(){const{methodId:i,braintreefastlane:n}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.braintreefastlane" argument is not provided.');if(!n.onInit||"function"!=typeof n.onInit)throw new gn('Unable to initialize payment because "options.braintreefastlane.onInit" argument is not provided or it is not a function.');if(!n.onChange||"function"!=typeof n.onChange)throw new gn('Unable to initialize payment because "options.braintreefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(i);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(i),{initializationData:a,clientToken:s}=o||{},{isFastlaneStylingEnabled:d}=a||{},c=Wt(r.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");this.is3DSEnabled=o.config.is3dsEnabled,s&&c&&this.braintreeSdk.initialize(s);const l=Po(d?null===(t=o.initializationData)||void 0===t?void 0:t.fastlaneStyles:void 0,n.styles);yield this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(i,l),this.shouldRunAuthenticationFlow()&&(yield this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow()),yield this.initializeCardComponent(),this.onError=n.onError,n.onInit(e=>this.renderBraintreeCardComponent(e)),n.onChange(()=>this.handleBraintreeStoredInstrumentChange(i))})}execute(e,t){return fl(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);yield this.paymentIntegrationService.submitOrder(n,t);const r=yield this.preparePaymentPayload(i.methodId);yield this.paymentIntegrationService.submitPayment(r),this.braintreeFastlaneUtils.removeSessionIdFromCookies()})}finalize(){return Promise.reject(new vd)}deinitialize(){return fl(this,void 0,void 0,function*(){return this.braintreeCardComponent=void 0,Promise.resolve()})}initializeCardComponent(){return fl(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState(),{phone:t,firstName:i,lastName:n}=e.getBillingAddressOrThrow(),r=`${i} ${n}`,o={styles:{},fields:Object.assign({cardholderName:{prefill:r,enabled:!0}},t&&{phoneNumber:{prefill:t}})},a=this.braintreeFastlaneUtils.getBraintreeFastlaneComponentOrThrow();this.braintreeCardComponent=yield a(o)})}renderBraintreeCardComponent(e){const t=this.getBraintreeCardComponentOrThrow();if(!e)throw new gn('Unable to initialize payment because "container" argument is not provided.');t.render(e)}preparePaymentPayload(e){var t,i;return fl(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),r=n.getBillingAddressOrThrow(),o=`${r.firstName} ${r.lastName}`,a=this.getPayPalInstruments()[0],s=yield this.braintreeFastlaneUtils.getDeviceSessionId(),d=Wt(n.getStoreConfigOrThrow().checkoutSettings.features,"PROJECT-7080.braintree_fastlane_three_ds");if(a){const t=this.is3DSEnabled&&d?yield this.get3DS(a.bigpayToken,(null==a?void 0:a.iin)||""):void 0;return{methodId:e,paymentData:{deviceSessionId:s,formattedPayload:{paypal_fastlane_token:{token:t||a.bigpayToken}}}}}const{getPaymentToken:c}=this.getBraintreeCardComponentOrThrow(),l=yield c({name:{fullName:o},billingAddress:this.mapToPayPalAddress(r)}),u=(null===(i=null===(t=l.paymentSource.card)||void 0===t?void 0:t.binDetails)||void 0===i?void 0:i.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 fl(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=yield this.braintreeSdk.getBraintreeThreeDS(),r=i.getOrderOrThrow();return new Promise((i,o)=>{n.verifyCard({amount:null==r?void 0:r.orderAmount,nonce:e,bin:t,onLookupComplete:(e,t)=>{n.on("customer-canceled",()=>{"function"==typeof this.onError&&this.onError(new Vn),o(new Vn)}),t()}},(e,t)=>(e&&"THREEDS_VERIFY_CARD_CANCELED_BY_MERCHANT"===e.code&&("function"==typeof this.onError&&this.onError(new Vn),o(new Vn)),i(t.nonce)))})})}mapToPayPalAddress(e){return{streetAddress:(null==e?void 0:e.address1)||"",locality:(null==e?void 0:e.city)||"",region:(null==e?void 0:e.stateOrProvinceCode)||(null==e?void 0:e.stateOrProvince)||"",postalCode:(null==e?void 0:e.postalCode)||"",countryCodeAlpha2:(null==e?void 0:e.countryCode)||""}}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getCustomerOrThrow(),n=e.getPaymentProviderCustomer(),r=vl(n)?n:{},o=this.braintreeFastlaneUtils.getSessionIdFromCookies();return!(!i.isGuest||(null==r?void 0:r.authenticationState)===Tn.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}getBraintreeCardComponentOrThrow(){if(!this.braintreeCardComponent)throw new pn;return this.braintreeCardComponent}getPayPalInstruments(){const e=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow();return(vl(e)?e:{}).instruments||[]}handleBraintreeStoredInstrumentChange(e){return fl(this,void 0,void 0,function*(){const t=this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow(),{selectionChanged:i,selectedCard:n}=yield t.profile.showCardSelector();if(i){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),i=vl(t)?t:{},r=this.braintreeFastlaneUtils.mapPayPalToBcInstrument(e,[n]);if(r&&r.length>0)return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},i),{instruments:[...r]})),r[0]}})}}const wl=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t),r=new To(e,n),o=new qn(a(),t,i),s=new Ln(o);return new Sl(e,r,s)},[{id:"braintreeacceleratedcheckout"}]);var Il=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class _l{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i}initialize(e){return Il(this,void 0,void 0,function*(){const{braintreevisacheckout:t,methodId:i}=e;if(!t)throw new gn('Unable to initialize payment because "options.braintreevisacheckout" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState();this.paymentMethod=n.getPaymentMethodOrThrow(i);const r=n.getCheckoutOrThrow(),o=n.getStoreConfigOrThrow(),{clientToken:a,config:s}=this.paymentMethod||{};if(!a)throw new Qi(Zi.MissingPaymentMethod);const{onError:d=V,onPaymentSelect:c=V}=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(i)])).then(()=>c()).catch(e=>d(e))),u.on("payment.error",(e,t)=>d(t))})}execute(e,t){var i,n;return Il(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!r)throw new gn('Unable to submit payment because "payload.payment" argument is not provided.');if(!(null===(n=null===(i=this.paymentMethod)||void 0===i?void 0:i.initializationData)||void 0===n?void 0:n.nonce))throw new Qi(Zi.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 vd)}deinitialize(){return Il(this,void 0,void 0,function*(){yield this.braintreeSdk.deinitialize()})}tokenizePayment(e,t){return Il(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.mapToVisaCheckoutAddress(n),billingAddress:a=this.mapToVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}mapToVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}handleError(e){if(e instanceof Error&&"BraintreeError"===e.name)throw new Kr(e.message);throw e}}const Cl=Rt(e=>{const t=window,i=new bn(e),n=new Ln(new qn(a(),t,i));return new _l(e,Ee(),n)},[{id:"braintreevisacheckout"}]);var bl=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Pl{constructor(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}initialize(e){return bl(this,void 0,void 0,function*(){const{methodId:t}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const i=this.paymentIntegrationService.getState();this.venmoOptions=e.braintreevenmo;const n=i.getPaymentMethodOrThrow(t);yield this.initializeBraintreeVenmo(n)})}execute(e){return bl(this,void 0,void 0,function*(){const{payment:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!t)throw new oo(["payment"]);try{const e=yield this.preparePaymentData(t);yield this.paymentIntegrationService.submitOrder(i),yield this.paymentIntegrationService.submitPayment(e)}catch(e){this.handleError(e)}})}finalize(){return Promise.reject(new vd)}deinitialize(){return bl(this,void 0,void 0,function*(){return yield this.braintreeIntegrationService.teardown(),Promise.resolve()})}handleError(e){if(!zn(e))throw e;if("PAYPAL_POPUP_CLOSED"===e.code)throw new Vn(e.message);throw new Kr(e.message)}initializeBraintreeVenmo(e){var t;return bl(this,void 0,void 0,function*(){const{clientToken:i}=e;if(!i)throw new Qi(Zi.MissingPaymentMethod);const n=Wt(this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features,"PAYPAL-5406.braintree_venmo_web_fallback_support");try{this.braintreeIntegrationService.initialize(i),this.braintreeVenmoCheckout=yield this.braintreeIntegrationService.getVenmoCheckout(Object.assign(Object.assign({},void 0!==(null===(t=this.venmoOptions)||void 0===t?void 0:t.allowDesktop)?{allowDesktop:this.venmoOptions.allowDesktop}:{}),n?{mobileWebFallBack:n}:{}))}catch(e){this.handleError(e)}})}preparePaymentData(e){return bl(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{nonce:i}=t.getPaymentMethodOrThrow(e.methodId);if(i)return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(i)});const n=yield this.braintreeVenmoTokenize(),r=yield this.braintreeIntegrationService.getSessionId();return Object.assign(Object.assign({},e),{paymentData:this.formattedPayload(n.nonce,n.details.email,r)})})}formattedPayload(e,t,i){return{formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:i||null,paypal_account:{token:e,email:t||null}}}}braintreeVenmoTokenize(){return new Promise((e,t)=>{var i;null===(i=this.braintreeVenmoCheckout)||void 0===i||i.tokenize((i,n)=>{if(i)return t(i);e(n)})})}}const Ol=Rt(e=>{const t=window,i=a(),n=new bn(e),r=new qn(i,t,n),o=new vo(r,t);return new Pl(e,o)},[{id:"braintreevenmo"}]);var El=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Al{constructor(e,t,i){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.braintreeHostedForm=i}initialize(e){return El(this,void 0,void 0,function*(){const{methodId:t,gatewayId:i,braintree:n}=e;yield this.paymentIntegrationService.loadPaymentMethod(t);const r=this.paymentIntegrationService.getState();this.paymentMethod=r.getPaymentMethodOrThrow(t);const{clientToken:o}=this.paymentMethod;if(!o)throw new Qi(Zi.MissingPaymentMethod);this.threeDSecure=null==n?void 0:n.threeDSecure,this.onPaymentError=null==n?void 0:n.onPaymentError;try{this.braintreeIntegrationService.initialize(o,this.threeDSecure),this.isHostedPaymentFormEnabled(t,i)&&(null==n?void 0:n.form)&&(yield this.braintreeHostedForm.initialize(n.form,n.unsupportedCardBrands,o),this.isHostedFormInitialized=this.braintreeHostedForm.isInitialized()),this.is3dsEnabled=this.paymentMethod.config.is3dsEnabled,this.deviceSessionId=yield this.braintreeIntegrationService.getSessionId(),this.shouldInitializeBraintreeFastlane()&&(yield this.initializeBraintreeFastlaneOrThrow(t))}catch(e){return this.handleError(e,t)}})}execute(e){return El(this,void 0,void 0,function*(){const{payment:t}=e,i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!t)throw new oo(["payment"]);this.isHostedFormInitialized&&this.braintreeHostedForm.validate(),yield this.paymentIntegrationService.submitOrder(i);const n=this.paymentIntegrationService.getState(),r=n.getBillingAddressOrThrow(),o=n.getOrderOrThrow().orderAmount;try{const e=this.isHostedFormInitialized?yield this.prepareHostedPaymentData(t,r,o):yield this.preparePaymentData(t,r,o);yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},t),{paymentData:e}))}catch(e){return this.processAdditionalAction(e,t,o)}})}finalize(){return Promise.reject(new vd)}deinitialize(){return El(this,void 0,void 0,function*(){return this.isHostedFormInitialized=!1,yield Promise.all([this.braintreeIntegrationService.teardown(),this.braintreeHostedForm.deinitialize()]),Promise.resolve()})}handleError(e,t){var i;if(dl(e)){if(!(t&&this.paymentIntegrationService.getState().isPaymentMethodInitialized({methodId:t})||"HOSTED_FIELDS_INVALID_FIELD_SELECTOR"!==e.code))return;if(e.code.startsWith("THREEDS_"))return null===(i=this.onPaymentError)||void 0===i||i.call(this,new Kr("THREEDS_VERIFICATION_FAILED")),Promise.reject();throw new Kr(e.message)}throw e}preparePaymentData(e,t,i){return El(this,void 0,void 0,function*(){const{paymentData:n}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e))return Object.assign(Object.assign({},r),n);const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=_d(n)?n:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.braintreeIntegrationService.verifyCard(e,t,i):yield this.braintreeIntegrationService.tokenizeCard(e,t);return Object.assign(Object.assign({},r),{nonce:s,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})})}prepareHostedPaymentData(e,t,i){return El(this,void 0,void 0,function*(){const{paymentData:n}=e,r={deviceSessionId:this.deviceSessionId};if(this.isSubmittingWithStoredCard(e)){const{nonce:e}=yield this.braintreeHostedForm.tokenizeForStoredCardVerification();return Object.assign(Object.assign(Object.assign({},r),n),{nonce:e})}const{shouldSaveInstrument:o=!1,shouldSetAsDefaultInstrument:a=!1}=_d(n)?n:{},{nonce:s}=this.shouldPerform3DSVerification(e)?yield this.verifyCardWithHostedForm(t,i):yield this.braintreeHostedForm.tokenize(t);return Object.assign(Object.assign({},r),{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a,nonce:s})})}prepareAdditionalActionPaymentData(e,t){const{paymentData:i}=e,n={deviceSessionId:this.deviceSessionId,nonce:t},{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=_d(i)?i:{};return this.isSubmittingWithStoredCard(e)&&(r||o)?Object.assign(Object.assign({},i),n):Object.assign({},n)}verifyCardWithHostedForm(e,t){return El(this,void 0,void 0,function*(){const i=yield this.braintreeHostedForm.tokenize(e);return this.braintreeIntegrationService.challenge3DSVerification(i,t)})}processAdditionalAction(e,t,i){return El(this,void 0,void 0,function*(){if(!ca(e)||!Z(e.body.errors,{code:"three_d_secure_required"}))return this.handleError(e);try{const{payer_auth_request:n}=function(e){return"object"==typeof e&&null!==e&&"name"in e&&"body"in e&&"status"in e.body&&"three_ds_result"in e.body&&"payer_auth_request"in e.body.three_ds_result&&"errors"in e.body}(e)&&e.body.three_ds_result||{},{paymentData:r}=t,o=this.paymentIntegrationService.getState();if(!r||!gd(r))throw new oo(["instrumentId"]);const a=o.getCardInstrumentOrThrow(r.instrumentId),{nonce:s}=yield this.braintreeIntegrationService.challenge3DSVerification({nonce:n||"",bin:a.iin},i),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||!gd(e.paymentData))}shouldPerform3DSVerification(e){return!(!this.is3dsEnabled||this.isSubmittingWithStoredCard(e))}shouldInitializeBraintreeFastlane(){var e;const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),i=vl(t)?t:{};return(null===(e=this.paymentMethod)||void 0===e?void 0:e.initializationData.isAcceleratedCheckoutEnabled)&&!(null==i?void 0:i.authenticationState)}initializeBraintreeFastlaneOrThrow(e){return El(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getPaymentMethodOrThrow(e),{clientToken:r,config:o}=n;if(!r)throw new Qi(Zi.MissingPaymentMethod);this.braintreeIntegrationService.initialize(r,this.threeDSecure),yield this.braintreeIntegrationService.getBraintreeFastlane(i.id,o.testMode)})}}function Tl(e){return"cardNumber"in e}function kl(e){if(!zn(e))return!1;const{details:t}=e;return void 0===t||"object"==typeof t&&null!==t&&void 0===t.invalidFieldKeys||(i=t,Array.isArray(i)&&i.every(e=>"string"==typeof e));var i}var Dl,Ml=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e[e.CreditCard=0]="CreditCard",e[e.StoredCardVerification=1]="StoredCardVerification"}(Dl||(Dl={}));class zl{constructor(e,t){this.braintreeScriptLoader=e,this.braintreeSDKVersionManager=t,this.isInitializedHostedForm=!1,this.handleBlur=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onBlur)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy),errors:this.mapErrors(e.fields)})},this.handleFocus=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onFocus)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleCardTypeChange=e=>{var t,i;const n=1===e.cards.length?e.cards[0].type.replace(/^master-card$/,"mastercard"):void 0;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onCardTypeChange)||void 0===i||i.call(t,{cardType:n})},this.handleInputSubmitRequest=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onEnter)||void 0===i||i.call(t,{fieldType:this.mapFieldType(e.emittedBy)})},this.handleValidityChange=e=>{var t,i;null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===i||i.call(t,{isValid:this.isValidForm(e),errors:this.mapValidationErrors(e.fields)})}}initialize(e,t,i){var n,r,o,a,s;return Ml(this,void 0,void 0,function*(){this.clientToken=i,this.formOptions=e,this.type=Tl(e.fields)?Dl.CreditCard:Dl.StoredCardVerification;const d=this.mapFieldOptions(e.fields,t);E(d)?this.isInitializedHostedForm=!1:(this.cardFields=yield this.createHostedFields({fields:d,styles:e.styles&&this.mapStyleOptions(e.styles)}),null===(n=this.cardFields)||void 0===n||n.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 Ml(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 nn(Xi.PaymentNotInitialized);const e=this.cardFields.getState();if(!this.isValidForm(e)){this.handleValidityChange(e);const t=this.mapValidationErrors(e.fields);throw new ao(t)}}tokenize(e){var t,i,n,r,o;return Ml(this,void 0,void 0,function*(){if(!this.cardFields)throw new nn(Xi.PaymentNotInitialized);try{const r=yield this.cardFields.tokenize(H({billingAddress:e&&this.mapBillingAddress(e)},k));return null===(i=null===(t=this.formOptions)||void 0===t?void 0:t.onValidate)||void 0===i||i.call(t,{isValid:!0,errors:{}}),{nonce:r.nonce,bin:null===(n=r.details)||void 0===n?void 0:n.bin}}catch(e){if(kl(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 ao(t)}throw e}})}tokenizeForStoredCardVerification(){var e,t,i,n,r;return Ml(this,void 0,void 0,function*(){if(!this.cardFields)throw new nn(Xi.PaymentNotInitialized);try{const n=yield this.cardFields.tokenize();return null===(t=null===(e=this.formOptions)||void 0===e?void 0:e.onValidate)||void 0===t||t.call(e,{isValid:!0,errors:{}}),{nonce:n.nonce,bin:null===(i=n.details)||void 0===i?void 0:i.bin}}catch(e){if(kl(e)){const t=this.mapTokenizeError(e,!0);if(t)throw null===(r=null===(n=this.formOptions)||void 0===n?void 0:n.onValidate)||void 0===r||r.call(n,{isValid:!1,errors:t}),new ao(t)}throw e}})}createHostedFields(e){return Ml(this,void 0,void 0,function*(){const t=yield this.getClient(),i=yield this.braintreeScriptLoader.loadHostedFields(),n=this.braintreeSDKVersionManager.getSDKVersion()===In?Object.assign(Object.assign({},e),{preventCursorJumps:!0}):e;return i.create(Object.assign(Object.assign({},n),{client:t}))})}getClient(){return Ml(this,void 0,void 0,function*(){if(!this.clientToken)throw new nn(Xi.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(Tl(e)){const i={};return null==t||t.forEach(e=>{(e=>Object.values(Mn).includes(e))(e)&&(i[e]=!1)}),H({number:Object.assign({container:`#${e.cardNumber.containerId}`,placeholder:e.cardNumber.placeholder,internalLabel:e.cardNumber.accessibilityLabel},Object.keys(i).length>0?{supportedCardBrands:i}:{}),expirationDate:{container:`#${e.cardExpiry.containerId}`,placeholder:e.cardExpiry.placeholder,internalLabel:e.cardExpiry.accessibilityLabel},cvv:e.cardCode&&{container:`#${e.cardCode.containerId}`,placeholder:e.cardCode.placeholder,internalLabel:e.cardCode.accessibilityLabel},cardholderName:{container:`#${e.cardName.containerId}`,placeholder:e.cardName.placeholder,internalLabel:e.cardName.accessibilityLabel}},k)}return H({number:e.cardNumberVerification&&{container:`#${e.cardNumberVerification.containerId}`,placeholder:e.cardNumberVerification.placeholder},cvv:e.cardCodeVerification&&{container:`#${e.cardCodeVerification.containerId}`,placeholder:e.cardCodeVerification.placeholder}},k)}mapStyleOptions(e){const t=(e={})=>H({color:e.color,"font-family":e.fontFamily,"font-size":e.fontSize,"font-weight":e.fontWeight},k);return{input:t(e.default),".invalid":t(e.error),":focus":t(e.focus)}}mapFieldType(e){switch(e){case"number":return this.type===Dl.StoredCardVerification?Fn.CardNumberVerification:Fn.CardNumber;case"expirationDate":return Fn.CardExpiry;case"cvv":return this.type===Dl.StoredCardVerification?Fn.CardCodeVerification:Fn.CardCode;case"cardholderName":return Fn.CardName;default:throw new Error("Unexpected field type")}}mapErrors(e){const t={};if(e)for(const[i,n]of Object.entries(e))if(n&&this.isValidParam(i)){const{isValid:e,isEmpty:r,isPotentiallyValid:o}=n;t[i]={isValid:e,isEmpty:r,isPotentiallyValid:o}}return t}mapValidationErrors(e){return Object.keys(e).reduce((t,i)=>{var n;return Object.assign(Object.assign({},t),{[this.mapFieldType(i)]:(null===(n=e[i])||void 0===n?void 0:n.isValid)?void 0:[this.createInvalidError(this.mapFieldType(i))]})},{})}mapTokenizeError(e,t=!1){var i,n;if("HOSTED_FIELDS_FIELDS_EMPTY"===e.code){const e=[this.createRequiredError(this.mapFieldType("cvv"))];return t?{[this.mapFieldType("cvv")]:e}:{[this.mapFieldType("cvv")]:e,[this.mapFieldType("expirationDate")]:[this.createRequiredError(this.mapFieldType("expirationDate"))],[this.mapFieldType("number")]:[this.createRequiredError(this.mapFieldType("number"))],[this.mapFieldType("cardholderName")]:[this.createRequiredError(this.mapFieldType("cardholderName"))]}}return null===(n=null===(i=e.details)||void 0===i?void 0:i.invalidFieldKeys)||void 0===n?void 0:n.reduce((e,t)=>{const i=this.mapFieldType(t);return Object.assign(Object.assign({},e),{[i]:[this.createInvalidError(i)]})},{})}createRequiredError(e){var t;return{fieldType:e,message:null!==(t={[Fn.CardCode]:"CVV is required",[Fn.CardCodeVerification]:"CVV is required",[Fn.CardNumber]:"Credit card number is required",[Fn.CardNumberVerification]:"Credit card number is required",[Fn.CardExpiry]:"Expiration date is required",[Fn.CardName]:"Full name is required"}[e])&&void 0!==t?t:"Field is required",type:"required"}}createInvalidError(e){var t,i,n,r;const o={[Fn.CardCode]:{message:"Invalid card code",type:"invalid_card_code"},[Fn.CardCodeVerification]:{message:"Invalid card code",type:"invalid_card_code"},[Fn.CardNumber]:{message:"Invalid card number",type:"invalid_card_number"},[Fn.CardNumberVerification]:{message:"Invalid card number",type:"invalid_card_number"},[Fn.CardExpiry]:{message:"Invalid card expiry",type:"invalid_card_expiry"},[Fn.CardName]:{message:"Invalid card name",type:"invalid_card_name"}};return{fieldType:e,message:null!==(i=null===(t=o[e])||void 0===t?void 0:t.message)&&void 0!==i?i:"Invalid field",type:null!==(r=null===(n=o[e])||void 0===n?void 0:n.type)&&void 0!==r?r:"invalid"}}isValidForm(e){return Object.keys(e.fields).every(t=>{var i;return null===(i=e.fields[t])||void 0===i?void 0:i.isValid})}isValidParam(e){return["number","cvv","expirationDate","postalCode","cardholderName","cardType"].includes(e)}}const Nl=Rt(e=>{const t=window,i=new bn(e),n=new qn(a(),t,i),r=new vo(n,t),o=new zl(n,i);return new Al(e,r,o)},[{id:"braintree"}]);var xl=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})},Fl=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i};class Rl{constructor(e){this._paymentIntegrationService=e}execute(e,t){var i,n;return this._isHostedPaymentFormEnabled(null===(i=e.payment)||void 0===i?void 0:i.methodId,null===(n=e.payment)||void 0===n?void 0:n.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,i=this._paymentIntegrationService.getState(),{paymentSettings:{bigpayBaseUrl:n=""}={}}=i.getStoreConfigOrThrow();if(!t)throw new gn;const r=this._paymentIntegrationService.createHostedForm(n,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 vd)}_executeWithoutHostedForm(e,t){return xl(this,void 0,void 0,function*(){const{payment:i}=e,n=Fl(e,["payment"]),r=i&&i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t),yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:r}))})}_executeWithHostedForm(e,t){return xl(this,void 0,void 0,function*(){const{payment:i}=e,n=Fl(e,["payment"]),r=this._hostedForm;if(!r)throw new nn(Xi.PaymentNotInitialized);if(!i||!i.methodId)throw new oo(["payment.methodId"]);yield this._paymentIntegrationService.submitOrder(n,t),yield r.validate().then(()=>r.submit(i))})}_isHostedPaymentFormEnabled(e,t){return!!e&&!0===this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!ne(e&&e.creditCard&&e.creditCard.form.fields).every(k)}}var Ll=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Bl extends Rl{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 Ll(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{methodId:i}=e;yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(i);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 Qi(Zi.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 nn(Xi.PaymentNotInitialized);if(!o||!s)throw new Qi(Zi.MissingPaymentMethod);if(this.sessionId=o,this.locale=n.getLocale(),!this.locale)throw new Qi(Zi.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 Kr("Failed to configure 3DS API.")},configuration:{userLanguage:this.locale,wsVersion:62}})}return Promise.resolve()})}execute(e,t){const i=Object.create(null,{execute:{get:()=>super.execute}});return Ll(this,void 0,void 0,function*(){const{payment:n}=e,r=n&&n.paymentData;if(!n||!r)throw new oo(["payment.paymentData"]);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n.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 i.execute.call(this,e,t).catch(e=>{if(!a||!ca(e)||!Z(e.body.errors,{code:"three_d_secure_required"}))return Promise.reject(e);const t=this.paymentIntegrationService.getState(),i=t.getOrder(),{storeProfile:{storeId:n}}=t.getStoreConfigOrThrow();if(!i||!this.sessionId)throw new Qi(Zi.MissingCheckout);const r=`${n}_${i.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 Qn;var o;const{three_ds_result:{token:s}}=e.body;return s?this.initiateAuthentication(r,s):Promise.reject(e)})})}finalize(e){return Ll(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===Gc.FINALIZE?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new vd)})}deinitialize(){return this.threeDSjs=void 0,this.sessionId="",super.deinitialize()}initiateAuthentication(e,t){return Ll(this,void 0,void 0,function*(){const i=yield new Promise((i,n)=>{if(!this.threeDSjs)throw new nn(Xi.PaymentNotInitialized);this.threeDSjs.initiateAuthentication(e,t,e=>{const t=e.error;return t?n(new Kr(t.msg)):this.threeDSjs&&"PROCEED"===e.gatewayRecommendation?i(e.restApiResponse):n(new Kr)})});if(i.transaction&&"AUTHENTICATION_AVAILABLE"===i.transaction.authenticationStatus)return this.authenticatePayer(e,t);throw new Kr})}authenticatePayer(e,t,i=1){return Ll(this,void 0,void 0,function*(){return new Promise((n,r)=>{if(!this.threeDSjs)return r(new nn(Xi.PaymentNotInitialized));this.threeDSjs.authenticatePayer(e,t,n=>Ll(this,void 0,void 0,function*(){const o=n.error;return o?o.cause&&"SERVER_BUSY"===o.cause&&i<5?(yield new Promise(e=>setTimeout(e,3e3)),this.authenticatePayer(e,t,++i)):r(new Kr):new Promise(V)}),{fullScreenRedirect:!0})})})}}class jl{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e){return t=this,i=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 pn;return this._window.ThreeDS},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}const Ul=Rt(e=>new Bl(e,new jl(a())),[{id:"cba_mpgs"}]);var ql;!function(e){e.OffsiteRedirect="offsite_redirect"}(ql||(ql={}));class Vl extends Rl{constructor(e){super(e),this.paymentIntegrationService=e}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===Gc.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new vd)}_executeWithHostedForm(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=this._hostedForm;if(!r)throw new nn(Xi.PaymentNotInitialized);if(!i||!i.methodId)throw new oo(["payment.methodId"]);try{yield r.validate(),yield this.paymentIntegrationService.submitOrder(n,t),yield r.submit(i)}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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_processResponse(e){if(!ca(e))return Promise.reject(e);const t=e.body.additional_action_required;return t&&t.type===ql.OffsiteRedirect?this._performRedirect(t):Promise.reject(e)}_performRedirect(e){return new Promise(()=>{window.location.replace(e.data.redirect_url)})}}class Gl extends Vl{_executeWithoutHostedForm(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=i&&i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_createFormattedPayload(e,t){if("fawry"===e&&"customerMobile"in t&&"customerEmail"in t){const e=t;return{customerMobile:e.customerMobile,customerEmail:e.customerEmail}}}}const Hl=Rt(e=>new Gl(e),[{gateway:"checkoutcom",id:"fawry"}]);function $l(e){return ca(e)&&Z(e.body.errors,{code:"three_d_secure_required"})}var Wl=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})},Yl=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i};class Kl extends Rl{constructor(e,t){super(e),this.paymentIntegrationService=e,this.formPoster=t}finalize(e){const t=this.paymentIntegrationService.getState();return t.getOrder()&&t.getPaymentStatus()===Gc.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),Promise.reject(new vd)}_executeWithoutHostedForm(e,t){return Wl(this,void 0,void 0,function*(){const{payment:i}=e,n=Yl(e,["payment"]),r=i&&i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this.paymentIntegrationService.submitOrder(n,t);try{yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:r}))}catch(e){return $l(e)?this._handleThreeDSecure(e):Promise.reject(e)}})}_executeWithHostedForm(e,t){return Wl(this,void 0,void 0,function*(){const{payment:i}=e,n=Yl(e,["payment"]),r=this._hostedForm;if(!r)throw new nn(Xi.PaymentNotInitialized);if(!i||!i.methodId)throw new oo(["payment.methodId"]);try{yield r.validate(),yield this.paymentIntegrationService.submitOrder(n,t),yield r.submit(i)}catch(e){return $l(e)?this._handleThreeDSecure(e):Promise.reject(e)}this.paymentIntegrationService.loadCurrentOrder()})}_handleThreeDSecure(e){const{acs_url:t,payer_auth_request:i,callback_url:n,merchant_data:r}=e.body.three_ds_result;return new Promise(()=>this.formPoster.postForm(t,{PaReq:i||null,TermUrl:n||null,MD:r||null}))}}const Jl=Rt(e=>new Kl(e,Ee()),[{gateway:"checkoutcom",id:"credit_card"},{gateway:"checkoutcom",id:"card"}]);class Zl extends Vl{_executeWithoutHostedForm(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=null==i?void 0:i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_createFormattedPayload(e,t){const i={iban:"",bic:""},{iban:n,bic:r}="iban"in t&&"bic"in t?t:i;return"sepa"===e&&document&&(i.iban=n,i.bic=r),i}}const Xl=Rt(e=>new Zl(e),[{gateway:"checkoutcom",id:"sepa"}]);class Ql extends Vl{_executeWithoutHostedForm(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=null==i?void 0:i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_createFormattedPayload(e,t){if("ideal"===e&&"bic"in t)return{bic:t.bic}}}const eu=Rt(e=>new Ql(e),[{gateway:"checkoutcom",id:"ideal"}]);const tu=["boleto","oxxo","qpay","ideal"];class iu extends Vl{_executeWithoutHostedForm(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=null==i?void 0:i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:Object.assign(Object.assign({},r),{formattedPayload:this._createFormattedPayload(i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_createFormattedPayload(e,t){const i={ccDocument:""},n="ccDocument"in t?t.ccDocument:"";return-1!==tu.indexOf(e)&&n&&(i.ccDocument=n),i}}const nu=Rt(e=>new iu(e),[{gateway:"checkoutcom"}]);var ru=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ou{constructor(e,t){this._paymentIntegrationService=e,this._clearpayScriptLoader=t}initialize(e){return ru(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:t}=this._paymentIntegrationService.getState(),i=t(e.methodId,e.gatewayId),n=this._paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features;this._clearpaySdk=yield this._clearpayScriptLoader.load(i,n)})}deinitialize(){return this._clearpaySdk=void 0,Promise.resolve()}execute(e,t){return ru(this,void 0,void 0,function*(){const{gatewayId:i,methodId:n}=e.payment||{};if(!i||!n)throw new oo(["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 gn("Unable to proceed because billing country is not supported.");return yield this._loadPaymentMethod(i,n,t),yield this._redirectToClearpay(a,this._paymentIntegrationService.getState().getPaymentMethod(n,i)),new Promise(V)})}finalize(e){var t,i,n;return ru(this,void 0,void 0,function*(){const r=this._paymentIntegrationService.getState(),o=r.getPaymentId(),a=r.getContextConfig();if(!o)throw new Qi(Zi.MissingCheckout);if(!a||!a.payment.token)throw new Qi(Zi.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(),ca(e))throw new Dd(null===(n=null===(i=null===(t=e.body)||void 0===t?void 0:t.errors)||void 0===i?void 0:i[0])||void 0===n?void 0:n.message)}})}_redirectToClearpay(e,t){return ru(this,void 0,void 0,function*(){if(!this._clearpaySdk||!t||!t.clientToken)throw new nn(Xi.PaymentNotInitialized);return this._clearpaySdk.initialize({countryCode:e}),this._clearpaySdk.redirect({token:t.clientToken}),Promise.resolve()})}_isCountrySupported(e){return"GB"===e}_loadPaymentMethod(e,t,i){var n;return ru(this,void 0,void 0,function*(){try{return yield this._paymentIntegrationService.loadPaymentMethod(e,Object.assign(Object.assign({},i),{params:Object.assign(Object.assign({},null==i?void 0:i.params),{method:t})}))}catch(e){if(e instanceof Qn&&422===(null===(n=e.body)||void 0===n?void 0:n.status))throw new gn("Clearpay can't process your payment for this order, please try another payment method");throw e}})}}class au{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t={}){return i=this,n=void 0,o=function*(){if(yield this._scriptLoader.loadScript(this._getScriptUrl(e.config.testMode,t)),!this._window.AfterPay)throw new pn;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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}_getScriptUrl(e,t={}){const i=Wt(t,"PI-4555.clearpay_add_https_to_prod_script",!1);return e?i?"https://portal.sandbox.clearpay.co.uk/afterpay-async.js":"//portal.sandbox.clearpay.co.uk/afterpay-async.js":i?"https://portal.clearpay.co.uk/afterpay-async.js":"//portal.clearpay.co.uk/afterpay-async.js"}}const su=Rt(e=>new ou(e,new au(a())),[{gateway:"clearpay"},{id:"clearpay"}]),du=Rt(e=>new Rl(e),[{default:!0}]);var cu=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class lu{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return cu(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,i,n){return cu(this,void 0,void 0,function*(){const{getCardInstrument:r,getPaymentMethodOrThrow:o}=this._paymentIntegrationService.getState(),{payment:{methodId:a="",paymentData:s={}}={}}=t,d=gd(s)&&r(s.instrumentId),c=d?d.iin:n&&n.getBin();c&&(yield this._cardinalClient.runBinProcess(c));try{return yield e(q(t,{payment:{paymentData:{threeDSecure:{token:o(a).clientToken}}}}),i)}catch(e){if(!ca(e)||!Z(e.body.errors,{code:"three_d_secure_required"}))throw e;const i=yield this._cardinalClient.getThreeDSecureData(e.body.three_ds_result,this._getOrderData());if(!n)return void(yield this._paymentIntegrationService.submitPayment(q(t.payment,{paymentData:{threeDSecure:i}})));yield n.submit(q(t.payment,{paymentData:{threeDSecure:i}}))}})}_getClientToken(e){return cu(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(),i=e.getShippingAddress(),n=e.getCheckoutOrThrow(),r=e.getOrderOrThrow();return{billingAddress:t,shippingAddress:i,currencyCode:n.cart.currency.code,id:r.orderId.toString(),amount:n.cart.cartAmount}}}const uu=[100004,1010,1011,1020];var hu,pu,mu,yu,gu,vu,fu;!function(e){e.SetupCompleted="payments.setupComplete",e.Validated="payments.validated"}(hu||(hu={})),function(e){e.Init="init",e.Complete="complete",e.Confirm="confirm"}(pu||(pu={})),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"}(yu||(yu={})),function(e){e.BinProcess="bin.process"}(gu||(gu={})),function(e){e.CCA="cca"}(vu||(vu={})),function(e){e.Yes="Y",e.No="N"}(fu||(fu={}));class Su{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(V)}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((i,n)=>{t.on(hu.SetupCompleted,()=>{t.off(hu.SetupCompleted),t.off(hu.Validated),this._configurationToken=e,i()}),t.on(hu.Validated,e=>{t.off(hu.SetupCompleted),t.off(hu.Validated),e.ActionCode===mu.Error&&(P(uu,e.ErrorNumber)&&n(new Qi(Zi.MissingPaymentMethod)),n(new Kr(e.ErrorDescription)))}),t.setup(pu.Init,{jwt:e})}))}runBinProcess(e){return this._getClientSDK().then(t=>t.trigger(gu.BinProcess,e).catch(V)).then(e=>{if(!e||!e.Status)throw new nn(Xi.PaymentNotInitialized)})}getThreeDSecureData(e,t){return this._getClientSDK().then(i=>new Promise((n,r)=>{i.on(hu.Validated,(e,t)=>{if(i.off(hu.Validated),!t)return r(new Kr(e.ErrorDescription?e.ErrorDescription:"An error was encountered while processing the transaction."));if(!e.ActionCode)return n({token:t});switch(e.ActionCode){case mu.Success:return n({token:t});case mu.NoAction:return e.ErrorNumber>0?r(new Kr(e.ErrorDescription)):e.Payment&&e.Payment.ExtendedData&&e.Payment.ExtendedData.SignatureVerification===fu.Yes?n({token:t}):r(new Kr("Transaction signature could not be validated."));case mu.Failure:return r(new Kr("User failed authentication or an error was encountered while processing the transaction."));case mu.Error:return r(new Kr(e.ErrorDescription))}});const o={AcsUrl:e.acs_url,Payload:e.merchant_data},a=this._mapToPartialOrder(t,e.payer_auth_request);i.continue(vu.CCA,o,a)}))}_mapToPartialOrder(e,t){const i={BillingAddress:this._mapToCardinalAddress(e.billingAddress)};return e.paymentData&&(i.Account=this._mapToCardinalAccount(e.paymentData)),e.billingAddress.email&&(i.Email1=e.billingAddress.email),e.shippingAddress&&(i.ShippingAddress=this._mapToCardinalAddress(e.shippingAddress)),{Consumer:i,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 nn(Xi.PaymentNotInitialized);return this._sdk}}class wu{constructor(e,t=window){this._scriptLoader=e,this._window=t}load(e,t){const i=t?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js";return this._scriptLoader.loadScript(`${i}?v=${e}`).then(()=>{if(!this._window.Cardinal)throw new pn;return this._window.Cardinal})}}var Iu=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class _u extends Rl{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Iu(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:i}=this._paymentIntegrationService.getState(),n=i(e.methodId);n.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(n))})}execute(e,t){const i=Object.create(null,{execute:{get:()=>super.execute}});return Iu(this,void 0,void 0,function*(){const{payment:{methodId:n=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(n).config.is3dsEnabled?this._threeDSecureFlow.start(i.execute.bind(this),e,t,this._hostedForm):i.execute.call(this,e,t)})}}const Cu=Rt(e=>new _u(e,new lu(e,new Su(new wu(a())))),[{id:"cybersource"}]);var bu=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Pu{constructor(e,t){this._paymentIntegrationService=e,this._cardinalClient=t}prepare(e){return bu(this,void 0,void 0,function*(){yield this._cardinalClient.load(e.id,e.config.testMode)})}start(e,t,i,n){var r,o,a,s;return bu(this,void 0,void 0,function*(){const{getCardInstrument:d}=this._paymentIntegrationService.getState(),{payment:c={methodId:""}}=t,{paymentData:l={}}=c;try{return yield e(t,i)}catch(e){if(ca(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,i=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,n);r&&(yield this._cardinalClient.runBinProcess(r));try{return yield this._submitPayment(c,{xid:i},n)}catch(e){if(ca(e)&&Z(e.body.errors,{code:"three_d_secure_required"})){const t=e.body.three_ds_result,i=null==t?void 0:t.payer_auth_request;return yield this._cardinalClient.getThreeDSecureData(t,this._getOrderData()),this._submitPayment(c,{token:i},n)}throw e}}throw e}})}_getOrderData(){const e=this._paymentIntegrationService.getState(),t=e.getBillingAddressOrThrow(),i=e.getShippingAddress(),{cart:{currency:{code:n},cartAmount:r}}=e.getCheckoutOrThrow();return{billingAddress:t,shippingAddress:i,currencyCode:n,id:e.getOrderOrThrow().orderId.toString(),amount:r}}_submitPayment(e,t,i){return bu(this,void 0,void 0,function*(){const n=q({},e,{paymentData:{threeDSecure:t}});i||(yield this._paymentIntegrationService.submitPayment(n)),yield null==i?void 0:i.submit(n)})}_getBin(e,t,i){const n=gd(e)&&t(e.instrumentId),r=function(e){const t=e;return!gd(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=i?i.getBin():r;return(n?n.iin:o)||""}}var Ou=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Eu extends Rl{constructor(e,t){super(e),this._threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Ou(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const{getPaymentMethodOrThrow:i}=this._paymentIntegrationService.getState(),n=i(e.methodId);n.config.is3dsEnabled&&(yield this._threeDSecureFlow.prepare(n))})}execute(e,t){const i=Object.create(null,{execute:{get:()=>super.execute}});return Ou(this,void 0,void 0,function*(){const{payment:{methodId:n=""}={}}=e,{getPaymentMethodOrThrow:r}=this._paymentIntegrationService.getState();return r(n).config.is3dsEnabled?this._threeDSecureFlow.start(i.execute.bind(this),e,t,this._hostedForm):i.execute.call(this,e,t)})}}const Au=Rt(e=>new Eu(e,new Pu(e,new Su(new wu(a())))),[{id:"cybersourcev2"},{id:"bnz"}]);class Tu{constructor(e,t){this._formPoster=e,this._paymentIntegrationService=t}execute(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=i&&i.paymentData;if(!i||!r)throw new oo(["payment.paymentData"]);yield this._paymentIntegrationService.submitOrder(n,t);try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},i),{paymentData:r}))}catch(e){if(!ca(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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}redirectUrl(e){return this._formPoster.postForm(e,{})}_isAdditionalActionRequired(e){const{additional_action_required:t,status:i}=e;return"additional_action_required"===i&&t&&"offsite_redirect"===t.type}}const ku=Rt(e=>new Tu(Ee(),e),[{id:"laybuy"}]);function Du(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 Mu=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class zu extends Jo{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,i){const n=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Mu(this,void 0,void 0,function*(){yield n.initialize.call(this,e,t,i);const r=n.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new Qi(Zi.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 Mu(this,void 0,void 0,function*(){const i=yield t.getNonce.call(this,e),n=t.getPaymentMethod.call(this);return JSON.stringify({type:n.method,googlePayToken:i,browser_info:Xa()})})}processAdditionalAction(e){return Mu(this,void 0,void 0,function*(){if(!ca(e)||!Du(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,i)=>{const n=JSON.parse(e.action);this._getAdyenClient().createFromAction(n,{onAdditionalDetails:e=>{const i={methodId:n.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(i)},size:"05",onError:e=>i(e)}).mount("body"),i(new Vn)})}_getAdyenClient(){if(!this._adyenClient)throw new nn(Xi.PaymentNotInitialized);return this._adyenClient}}var Nu=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class xu{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t,this._isDeinitializationBlocked=!1,this._loadingIndicator=new td({containerStyles:Qs})}initialize(e){var t;return Nu(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId)||!Xo(e.methodId))throw new gn('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 gn("Unable to proceed without valid options.");const{walletButton:n,loadingContainerId:r}=i,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(i,["walletButton","loadingContainerId"]);this._loadingIndicatorContainer=r,yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());const a=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(this._getMethodId());yield this._googlePayPaymentProcessor.initialize(()=>a,this._getGooglePayClientOptions(null===(t=a.initializationData)||void 0===t?void 0:t.storeCountry)),this._addPaymentButton(n,o)})}execute({payment:e}){return Nu(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new oo(["payment"]);yield this._paymentIntegrationService.submitOrder();const t=yield this._googlePayPaymentProcessor.getNonce(e.methodId),i=yield this._googlePayPaymentProcessor.extraPaymentData();try{yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign({nonce:t},i)}))}catch(t){yield this._googlePayPaymentProcessor.processAdditionalAction(t,e.methodId)}})}finalize(){return Promise.reject(new vd)}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 i=document.getElementById(e);if(!i)throw new gn("Unable to proceed without a walletButton.");this._paymentButton=i,this._clickListener=this._handleClick(t),this._paymentButton.addEventListener("click",this._clickListener)}_handleClick({onPaymentSelect:e,onError:t}){return i=>Nu(this,void 0,void 0,function*(){i.preventDefault();try{this._googlePayPaymentProcessor.setShouldRequestShipping(!1),yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(e){let i=e;if(this._toggleLoadingIndicator(!1),Zo(e)){if("CANCELED"===e.statusCode)throw new Vn;i=new Kr(JSON.stringify(e))}throw null==t||t(new Kr("An error occurred while requesting your Google Pay payment details.")),i}finally{this._toggleBlockDeinitialization(!1)}null==e||e()})}_interactWithPaymentSheet(){return Nu(this,void 0,void 0,function*(){const e=yield this._googlePayPaymentProcessor.showPaymentSheet();this._toggleBlockDeinitialization(!0),this._toggleLoadingIndicator(!0);const t=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(e);t&&(yield this._paymentIntegrationService.updateBillingAddress(t)),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 tn(this._methodId,()=>new nn(Xi.PaymentNotInitialized))}_getIsSignedInOrThrow(){return Nu(this,void 0,void 0,function*(){try{return!!(yield this._googlePayPaymentProcessor.getNonce(this._getMethodId()))}catch(e){if(e instanceof Qi&&e.subtype===Zi.MissingPaymentToken)return!1;throw e}})}_handleOfferTrigger(e){return Nu(this,void 0,void 0,function*(){let t=!1,i="Sign in to Google Pay first to apply or remove promo codes.";try{t=yield this._getIsSignedInOrThrow()}catch(e){e instanceof Qi&&(i=e.message)}if(t){const{newOfferInfo:t,error:i}=yield this._googlePayPaymentProcessor.handleCoupons(e);return{newOfferInfo:t,error:i}}return{error:{reason:Ho.OFFER_INVALID,message:i,intent:$o.OFFER}}})}_getGooglePayClientOptions(e){return{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:t,offerData:i})=>Nu(this,void 0,void 0,function*(){if(t!==$o.INITIALIZE&&t!==$o.OFFER)return;const{offerChangeTriggers:n}=this._googlePayPaymentProcessor.getCallbackTriggers(),{newOfferInfo:r,error:o}=n.includes(t)?yield this._handleOfferTrigger(i):{},a=o;yield this._paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:s,getCartOrThrow:d}=this._paymentIntegrationService.getState(),{code:c,decimalPlaces:l}=d().currency,u=J(s().outstandingBalance,l).toFixed(l);return Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},e&&{countryCode:e}),{currencyCode:c,totalPriceStatus:qo.FINAL,totalPrice:u})},r&&{newOfferInfo:r}),a&&{error:a})})}}}_toggleBlockDeinitialization(e){this._isDeinitializationBlocked=e}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this._loadingIndicator.show(this._loadingIndicatorContainer):this._loadingIndicator.hide()}}const Fu=Rt(e=>new xu(e,new ia(ra(),new zu(e,new md(a(),s())),i(),Ee())),[{id:"googlepayadyenv2"}]);var Ru=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Lu extends Jo{constructor(e,t){super("adyen",e),this._scriptLoader=t,this._service=e}initialize(e,t,i){const n=Object.create(null,{initialize:{get:()=>super.initialize},getPaymentMethod:{get:()=>super.getPaymentMethod}});return Ru(this,void 0,void 0,function*(){yield n.initialize.call(this,e,t,i);const r=n.getPaymentMethod.call(this),o=this._service.getState().getStoreConfig();if(!o)throw new Qi(Zi.MissingCheckoutConfig);return this._adyenClient=yield this._scriptLoader.load({environment:r.config.testMode?"test":"live",locale:o.storeProfile.storeLanguage}),Promise.resolve()})}processAdditionalAction(e){return Ru(this,void 0,void 0,function*(){if(!ca(e)||!Du(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 Ru(this,void 0,void 0,function*(){const i=yield t.getNonce.call(this,e),n=t.getPaymentMethod.call(this);return JSON.stringify({type:n.method,googlePayToken:i,browser_info:Xa()})})}_handleAction(e){return new Promise((t,i)=>{const n=JSON.parse(e.action);this._getAdyenClient().createFromAction(n,{onAdditionalDetails:e=>{const i={methodId:n.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};t(i)},size:"05",onError:e=>i(e)}).mount("body"),i(new Vn)})}_getAdyenClient(){if(!this._adyenClient)throw new nn(Xi.PaymentNotInitialized);return this._adyenClient}}const Bu=Rt(e=>new xu(e,new ia(ra(),new Lu(e,new Id(a(),s())),i(),Ee())),[{id:"googlepayadyenv3"}]),ju=Rt(e=>new xu(e,new ia(ra(),new sa(e),i(),Ee())),[{id:"googlepayauthorizenet"}]),Uu=Rt(e=>{const t=i();return new xu(e,new ia(ra(),new ha(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),qu=Rt(e=>new xu(e,new ia(ra(),new ma(e),i(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),Vu=Rt(e=>new xu(e,new ia(ra(),new va(e),i(),Ee())),[{id:"googlepayorbital"}]),Gu=Rt(e=>new xu(e,new ia(ra(),new xa(e,new ka(a())),i(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),Hu=Rt(e=>new xu(e,new ia(ra(),new La(e),i(),Ee())),[{id:"googlepayworldpayaccess"}]),$u=Rt(e=>{const t=i(),n=window,r=new bn(e),o=new Ln(new qn(a(),n,r));return new xu(e,new ia(ra(),new Ua(e,o),t,Ee()))},[{id:"googlepaybraintree"}]);var Wu,Yu;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(Wu||(Wu={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Yu||(Yu={}));var Ku=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ju extends xu{constructor(e,t,i,n){super(e,t),this._payPalCommerceSdk=i,this._requestSender=n}execute({payment:e}){return Ku(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new oo(["payment"]);const t=this._paymentIntegrationService.getState(),i=t.getCartOrThrow().id,{initializationData:n}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(i),{card_information:o}=n||{},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 Ku(this,void 0,void 0,function*(){const i=this._paymentIntegrationService.getState(),n=i.getPaymentMethodOrThrow(this._getMethodId());if(!n.initializationData)throw new Qi(Zi.MissingPaymentMethod);const r=i.getCartOrThrow().currency.code,o=yield this._payPalCommerceSdk.getPayPalGooglePaySdk(n,r,!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===Wu.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==Wu.Approved)throw new gn("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return Ku(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:i}=yield this._requestSender.post("/api/storefront/payments/googlepaypaypalcommercecheckout",{headers:Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr),body:t});return i})}}const Zu=Rt(e=>{const t=new Ga(a());return new Ju(e,new ia(ra(),new Wa(e,t),i(),Ee()),t,i())},[{id:"googlepaypaypalcommerce"}]);var Xu,Qu;!function(e){e.Approved="APPROVED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(Xu||(Xu={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Qu||(Qu={}));var eh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class th extends xu{constructor(e,t,i,n){super(e,t),this._payPalSdkHelper=i,this._requestSender=n}execute({payment:e}){return eh(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new oo(["payment"]);const t=this._paymentIntegrationService.getState(),i=t.getCartOrThrow().id,{initializationData:n}=t.getPaymentMethodOrThrow(this._getMethodId()),{orderId:r}=yield this.getOrderId(i),{card_information:o}=n||{},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 eh(this,void 0,void 0,function*(){const i=this._paymentIntegrationService.getState(),n=i.getPaymentMethodOrThrow(this._getMethodId());if(!n.initializationData)throw new Qi(Zi.MissingPaymentMethod);const r=i.getCartOrThrow().currency.code,o=yield this._payPalSdkHelper.getPayPalGooglePaySdk(n,r,!0),{status:a}=yield o.Googlepay().confirmOrder({orderId:e,paymentMethodData:t});if(a===Xu.PayerActionRequired)return yield o.Googlepay().initiatePayerAction({orderId:e}),Promise.resolve();if(a!==Xu.Approved)throw new gn("Payment is not approved.");return Promise.resolve()})}getOrderId(e){return eh(this,void 0,void 0,function*(){const t={cartId:e,shouldSaveInstrument:!1},{body:i}=yield this._requestSender.post("/api/storefront/payments/googlepay_bigcommerce_paymentscheckout",{headers:Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr),body:t});return i})}}const ih=Rt(e=>{const t=new Mr(a());return new th(e,new ia(ra(),new Ja(e,t),i(),Ee()),t,i())},[{id:"googlepay_bigcommerce_payments"}]),nh=Rt(e=>new xu(e,new ia(ra(),new es(e,Ee()),i(),Ee())),[{id:"googlepaytdonlinemart"}]);class rh extends Ji{constructor(e,t,i){super(i||"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 oh{constructor(e,t){this.paymentIntegrationService=e,this.formPoster=t}execute(e,t){var i,n,r,o,a;return n=this,r=void 0,a=function*(){const{payment:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!(null==n?void 0:n.methodId))throw new oo(["payment.methodId"]);yield this.paymentIntegrationService.loadPaymentMethod(n.methodId,t);const o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n.methodId);if(!(null===(i=o.initializationData)||void 0===i?void 0:i.processable))throw new rh("payment.humm_not_processable_error","hummNotProcessableError");yield this.paymentIntegrationService.submitOrder(r,t);try{yield this.paymentIntegrationService.submitPayment({methodId:n.methodId})}catch(e){return this.isOffsiteRedirectResponse(e)?this.handleOffsiteRedirectResponse(e):Promise.reject(e)}},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())})}finalize(){return Promise.reject(new vd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}handleOffsiteRedirectResponse(e){const t=e.body.additional_action_required.data.redirect_url,i=e.body.provider_data;return new Promise(e=>{this.formPoster.postForm(t,JSON.parse(i),e)})}isOffsiteRedirectResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!t.body)return!1;const i=t.body;return"additional_action_required"===i.status&&!!i.additional_action_required&&"offsite_redirect"===i.additional_action_required.type&&"string"==typeof i.provider_data}}const ah=Rt(e=>new oh(e,Ee()),[{id:"humm"}]),sh=["AT","BE","CA","CH","CZ","DE","DK","ES","FI","FR","GB","GR","IE","IT","NL","NO","NZ","PL","PT","SE"],dh=["AU"];var ch=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class lh{constructor(e,t){this.paymentIntegrationService=e,this.klarnaScriptLoader=t}initialize(e){return ch(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 ch(this,void 0,void 0,function*(){if(!e.payment)throw new gn('Unable to proceed because "payload.payment" argument is not provided.');const i=e.payment,{paymentData:n}=i,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(i,["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 vd)}loadWidget(e){return ch(this,void 0,void 0,function*(){if(!e.klarna)throw new gn('Unable to load widget because "options.klarna" argument is not provided.');const{methodId:t,klarna:{container:i,onLoad:n}}=e;return yield this.paymentIntegrationService.loadPaymentMethod(t),new Promise(e=>{const r=this.paymentIntegrationService.getState().getPaymentMethod(t);if(!r)throw new Qi(Zi.MissingPaymentMethod);if(!this.klarnaCredit||!r.clientToken)throw new nn(Xi.PaymentNotInitialized);this.klarnaCredit.init({client_token:r.clientToken}),this.klarnaCredit.load({container:i},t=>{n&&n(t),e(t)})})})}getUpdateSessionData(e,t){if(!P([...sh,...dh],e.countryCode))return{};const i={billing_address:this.mapToKlarnaAddress(e,e.email)};return t&&(i.shipping_address=this.mapToKlarnaAddress(t,e.email)),i}needsStateCode(e){return P(dh,e)}mapToKlarnaAddress(e,t){const i={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&&(i.street_address2=e.address2),e.phone&&(i.phone=e.phone),i}authorize(){return new Promise((e,t)=>{const i=this.paymentIntegrationService.getState(),n=i.getBillingAddress(),r=i.getShippingAddress();if(!n)throw new Qi(Zi.MissingBillingAddress);if(!this.klarnaCredit)throw new nn(Xi.PaymentNotInitialized);const o=this.getUpdateSessionData(n,r);this.klarnaCredit.authorize(o,i=>i.approved?e(i):i.show_form?t(new Vn):void t(new Jr))})}}class uh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,i,n,r,o;return i=this,n=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 pn;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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())})}}const hh=Rt(e=>new lh(e,new uh(a())),[{id:"klarna"}]);var ph=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class mh{constructor(e,t,i){this.paymentIntegrationService=e,this.klarnav2ScriptLoader=t,this.klarnav2TokenUpdater=i}initialize(e){return ph(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 ph(this,void 0,void 0,function*(){if(!e.payment)throw new gn('Unable to proceed because "payload.payment" argument is not provided.');const i=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e.payment,[]),{gatewayId:n,methodId:r}=i;if(!n)throw new gn('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,n,r),{authorization_token:u}=yield this.authorizeOrThrow(l,r);yield this.paymentIntegrationService.initializePayment(n,{authorizationToken:u}),yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:i,useStoreCredit:e.useStoreCredit}),t)})}finalize(){return Promise.reject(new vd)}loadPaymentsWidget(e){return ph(this,void 0,void 0,function*(){if(!e.klarnav2)throw new gn('Unable to load widget because "options.klarnav2" argument is not provided.');const{methodId:t,gatewayId:i,klarnav2:{container:n,onLoad:r}}=e;if(!i)throw new gn('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(i,{params:a}).catch(()=>{throw new Qi(Zi.MissingPaymentMethod)}),new Promise(e=>{const a=o.getPaymentMethodOrThrow(t),{klarnaMultipleRadioButton:s}=a.initializationData||{};if(!this.klarnaPayments||!a.clientToken)throw new nn(Xi.PaymentNotInitialized);this.klarnaPayments.init({client_token:a.clientToken}),this.klarnaPayments.load({container:n,payment_method_category:this.isKlarnaMultipleRadioButtonEnabled(s,i,t)},t=>{r&&r(t),e(t)})})})}getUpdateSessionData(e,t,i){if(!P([...sh,...dh],t.countryCode))return{};const n={billing_address:this.mapToKlarnaAddress(e,t,t.email)};return i&&(n.shipping_address=this.mapToKlarnaAddress(e,i,t.email)),n}needsStateCode(e){return P(dh,e)}isKlarnaMultipleRadioButtonEnabled(e,t,i){return e?i:t}mapToKlarnaAddress(e,t,i){const n=this.paymentIntegrationService.getState(),{checkoutSettings:r}=n.getStoreConfigOrThrow(),o=n.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:i};return t.address2&&(s.street_address2=t.address2),t.phone&&(s.phone=t.phone),t.company&&a&&Wt(r.features,"PI-3915.b2b_payment_session_for_klarna")&&(s.organization_name=t.company),s}authorizeOrThrow(e,t){return ph(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const i=this.paymentIntegrationService.getState(),n=i.getBillingAddressOrThrow(),r=i.getShippingAddress(),o=this.getUpdateSessionData(t,n,r);return new Promise((t,i)=>{if(!this.klarnaPayments)return i(new nn(Xi.PaymentNotInitialized));this.klarnaPayments.authorize({payment_method_category:e},o,e=>e.approved?t(e):e.show_form?i(new Vn):void i(new Jr))})})}}class yh{constructor(e,t=window){this.scriptLoader=e,this.klarnaWindow=t}load(){var e,t,i,n,r,o;return i=this,n=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 pn;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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())})}}class gh{constructor(e){this.requestSender=e}updateClientToken(e,{timeout:t,params:i}={}){const n=`/api/storefront/payments/${e}`;return this.requestSender.get(n,{timeout:t,headers:Object.assign({Accept:ur.JsonV1,"X-API-INTERNAL":cr},hr),params:i})}klarnaOrderInitialization(e,t){return i=this,n=void 0,o=function*(){const i={headers:Object.assign({Accept:ur.JsonV1,"X-API-INTERNAL":cr},hr),body:{cartId:e,clientToken:t}};yield this.requestSender.put("/api/storefront/initialization/klarna",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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}const vh=Rt(e=>{const{getHost:t}=e.getState(),n=i({host:t()});return new mh(e,new yh(a()),new gh(n))},[{gateway:"klarna"}]);class fh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return i=this,n=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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Sh=Rt(e=>new fh(e),[{id:"testgateway"}]);var wh,Ih=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e.CREDIT_CARD="credit_card"}(wh||(wh={}));const _h=["klarnapaylater","klarnasliceit"];class Ch{constructor(e,t){this.mollieScriptLoader=e,this.paymentIntegrationService=t}initialize(e){return Ih(this,void 0,void 0,function*(){const{mollie:t,methodId:i,gatewayId:n}=e;if(!t)throw new gn('Unable to initialize payment because "options.mollie" argument is not provided.');if(!i||!n)throw new gn('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.');const r=document.querySelectorAll(".mollie-components-controller");v(r,e=>e.remove());const o=this.paymentIntegrationService.getState(),a=o.getStoreConfigOrThrow();this.initializeOptions=t;const s=o.getPaymentMethodOrThrow(i,n),{config:{merchantId:d,testMode:c}}=s;if(this.locale=o.getLocale(),!d)throw new Qi(Zi.MissingPaymentMethod);return this.isCreditCard(i)&&t.form&&this.shouldShowTSVHostedForm(i,n)?this.hostedForm=yield this.mountCardVerificationfields(t.form):this.isCreditCard(i)&&(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(`${n}-${i}-paragraph`);e&&e.remove(),t.disableButton(!1),this.loadPaymentMethodsAllowed(t,i,n)}},this.unsubscribe(),this.loadPaymentMethodsAllowed(t,i,n),Promise.resolve()})}execute(e,t){return Ih(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=null==i?void 0:i.paymentData;if(!i||!i.gatewayId||!r)throw new oo(["payment","gatewayId","paymentData"]);try{return yield this.paymentIntegrationService.submitOrder(n,t),gd(r)?yield this.executeWithVaulted(i):this.isCreditCard(i.methodId)?yield this.executeWithCC(i):yield this.executeWithAPM(i)}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 Ih(this,void 0,void 0,function*(){const t=e.paymentData,{shouldSaveInstrument:i=!1,shouldSetAsDefaultInstrument:n=!1}=_d(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:i,set_as_default_stored_instrument:n,browser_info:Xa(),shopper_locale:this.getShopperLocale()};yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:a}}))})}executeWithVaulted(e){return Ih(this,void 0,void 0,function*(){if(this.isHostedPaymentFormEnabled(e.methodId,e.gatewayId)){const t=this.hostedForm;if(!t)throw new nn(Xi.PaymentNotInitialized);yield t.validate(),yield t.submit(e),yield this.paymentIntegrationService.loadCurrentOrder()}else yield this.paymentIntegrationService.submitPayment(e)})}executeWithAPM(e){return Ih(this,void 0,void 0,function*(){const t=e.paymentData,i=t&&"issuer"in t?t.issuer:"";yield this.paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:Object.assign(Object.assign({},t),{formattedPayload:{issuer:i,shopper_locale:this.getShopperLocale()}})}))})}isCreditCard(e){return e===wh.CREDIT_CARD}shouldShowTSVHostedForm(e,t){return this.isHostedPaymentFormEnabled(e,t)&&this.isHostedFieldAvailable()}mountCardVerificationfields(e){return new Promise((t,i)=>Ih(this,void 0,void 0,function*(){try{const i=this.paymentIntegrationService.getState().getStoreConfig(),n=null==i?void 0:i.paymentSettings.bigpayBaseUrl;if(!n)throw new Qi(Zi.MissingCheckoutConfig);const r=this.paymentIntegrationService.createHostedForm(n,e);yield r.attach(),t(r)}catch(e){i(e)}}))}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:i}=this.paymentIntegrationService.getState();return!0===i(e,t).config.isHostedFormEnabled}isHostedFieldAvailable(){var e;return!!(null===(e=this.getInitializeOptions().form)||void 0===e?void 0:e.fields)}processAdditionalAction(e){if(!ca(e))return Promise.reject(e);if(Z(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 nn(Xi.PaymentNotInitialized);return this.initializeOptions}loadMollieJs(e,t,i=!1){return this.mollieClient?Promise.resolve(this.mollieClient):this.mollieScriptLoader.load(e,t,i)}getMollieClient(){if(!this.mollieClient)throw new nn(Xi.PaymentNotInitialized);return this.mollieClient}getShopperLocale(){if(!this.locale)throw new nn(Xi.PaymentNotInitialized);return this.locale}mountElements(){const{containerId:e,cardNumberId:t,cardCvcId:i,cardExpiryId:n,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(`#${i}`),this.expiryDateElement=e.createComponent("expiryDate",{styles:o}),this.expiryDateElement.mount(`#${n}`)}},0)}loadPaymentMethodsAllowed(e,t,i){var n;if(_h.includes(t)){const r=null===(n=this.paymentIntegrationService.getState().getCartOrThrow().lineItems)||void 0===n?void 0:n.digitalItems;if(r&&r.length>0){const{containerId:n}=this.getInitializeOptions();if(n){const r=document.getElementById(n);if(r){const n=document.createElement("p");n.setAttribute("id",`${i}-${t}-paragraph`),e.unsupportedMethodMessage&&(n.innerText=e.unsupportedMethodMessage,r.appendChild(n),e.disableButton(!0))}}}}}}class bh{constructor(e,t=window){this.scriptLoader=e,this.mollieHostWindow=t}load(e,t,i){return n=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 pn;return this.mollieHostWindow.Mollie(e,{locale:t,testmode:i})},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())});var n,r,o,a}}const Ph=Rt(e=>new Ch(new bh(a()),e),[{gateway:"mollie"},{gateway:"mollie",id:"applepay"}]);var Oh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};const Eh="moneris-payment-iframe";class Ah{constructor(e){this.paymentIntegrationService=e}initialize(e){return Oh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),{moneris:i,methodId:n}=e;if(!n)throw new gn('Unable to initialize payment because "methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.moneris" argument is not provided.');this.initializeOptions=i;const{config:r,initializationData:o}=t.getPaymentMethodOrThrow(n);if(!(null==o?void 0:o.profileId))throw new Qi(Zi.MissingPaymentMethod);return i.form&&this.shouldShowTSVHostedForm(n)&&(this.hostedForm=yield this.mountCardVerificationfields(i.form)),this.iframe||(this.iframe=this.createIframe(i.containerId,o,!!r.testMode)),Promise.resolve()})}execute(e,t){return Oh(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{isStoreCreditApplied:r}=this.paymentIntegrationService.getState().getCheckoutOrThrow();if(r&&(yield this.paymentIntegrationService.applyStoreCredit(r)),yield this.paymentIntegrationService.submitOrder(n,t),!i.paymentData||!gd(i.paymentData))return this.executeWithCC(i);yield this.executeWithVaulted(i)})}finalize(){return Promise.reject(new vd)}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 Oh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId).config.testMode,i=e.paymentData||{},n=_d(i)?i:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o}=n,a=yield new Promise((e,i)=>{if(!this.iframe)throw new nn(Xi.PaymentNotInitialized);const n=this.iframe.contentWindow;if(null===n)throw new nn(Xi.PaymentNotInitialized);n.postMessage("tokenize",this.monerisURL(!!t)),this.windowEventListener=n=>{if("string"==typeof n.data&&n.origin===`https://${t?"esqa":"www3"}.moneris.com`)try{e(this.handleMonerisResponse(n))}catch(e){i(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 Oh(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(),i=H(null===(e=t.form)||void 0===e?void 0:e.fields,E);return!E(i)}getInitializeOptions(){if(!this.initializeOptions)throw new nn(Xi.PaymentNotInitialized);return this.initializeOptions}mountCardVerificationfields(e){var t;return Oh(this,void 0,void 0,function*(){const i=null===(t=this.paymentIntegrationService.getState().getStoreConfig())||void 0===t?void 0:t.paymentSettings.bigpayBaseUrl;if(!i)throw new Qi(Zi.MissingCheckoutConfig);const n=this.paymentIntegrationService.createHostedForm(i,e);return yield n.attach(),n})}createIframe(e,t,i,n){const r=document.getElementById(e);if(!r)throw new gn("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==n?void 0:n.cssBody)||"font-family: Arial, Helvetica,sans-serif;background: transparent;",css_textbox:(null==n?void 0:n.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==n?void 0:n.cssTextboxCardNumber)||"width: 240px;",css_textbox_exp:(null==n?void 0:n.cssTextboxExpiryDate)||"margin-bottom: 0;width: calc(30% - 12px);",css_textbox_cvd:(null==n?void 0:n.cssTextboxCVV)||"margin-bottom: 0;width: calc(30% - 12px);",css_input_label:(null==n?void 0:n.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=B(a,(e,t)=>`${t}=${e}`).join("&");return o.width="100%",o.height="100%",o.name=Eh,o.id=Eh,o.style.border="none",o.src=`${this.monerisURL(i)}?${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 Th=Rt(e=>new Ah(e),[{id:"moneris"}]);class kh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return i=this,n=void 0,o=function*(){yield this._paymentIntegrationService.submitOrder(G(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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const Dh=Rt(e=>new kh(e),[{id:"nopaymentdatarequired"}]);class Mh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return i=this,n=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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}}const zh=Rt(e=>new Mh(e),[{type:"PAYMENT_TYPE_OFFLINE"}]);var Nh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class xh{constructor(e){this._paymentIntegrationService=e}execute(e,t){return Nh(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),r=this._shouldSubmitFullPayload(i)?e:n,o=i&&i.paymentData,a=o&&gd(o)&&o.instrumentId||void 0,s=o&&_d(o)&&o.shouldSaveInstrument||void 0,d=o&&_d(o)&&o.shouldSetAsDefaultInstrument||void 0;if(!i)throw new oo(["payment"]);const{methodId:c,gatewayId:l}=i;yield this._paymentIntegrationService.submitOrder(r,t),yield this._paymentIntegrationService.initializeOffsitePayment({methodId:c,gatewayId:l,instrumentId:a,shouldSaveInstrument:s,shouldSetAsDefaultInstrument:d})})}finalize(e){return Nh(this,void 0,void 0,function*(){const t=this._paymentIntegrationService.getState(),i=t.getOrder(),n=t.getPaymentStatus();if(!i||n!==Gc.ACKNOWLEDGE&&n!==Gc.FINALIZE)return Promise.reject(new vd);yield this._paymentIntegrationService.finalizeOrder(e)})}initialize(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_shouldSubmitFullPayload(e){return!!e&&("adyen"===e.gatewayId||"barclaycard"===e.gatewayId)}}const Fh=Rt(e=>new xh(e),[{type:"PAYMENT_TYPE_HOSTED"}]),Rh={"background-color":"rgba(0, 0, 0, 0.4)","z-index":"1000"},Lh=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 Bh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class jh{constructor(e,t,i,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalCommerceSdk=i,this.loadingIndicator=n}initialize(e){var t;return Bh(this,void 0,void 0,function*(){const{methodId:i,paypalcommerce:n}=e||{};if(this.paypalcommerce=n,!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(i),{container:a,bannerContainerId:s}=n,{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.paypalCommerceSdk.getPayPalMessages(o,r.getCartOrThrow().currency.code);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.paypalCommerceIntegrationService.loadPayPalSdk(i),n.onInit&&"function"==typeof n.onInit&&n.onInit(()=>this.renderButton(i,n)),(void 0===n.shouldRenderPayPalButtonOnInitialization||n.shouldRenderPayPalButtonOnInitialization)&&this.renderButton(i,n))})}execute(e,t){var i,n;return Bh(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{onError:a}=this.paypalcommerce||{};if(!r)throw new oo(["payment"]);const{methodId:s,paymentData:d}=r;if(this.isPayPalVaultedInstrumentPaymentData(d)&&!this.orderId&&(this.orderId=yield this.createOrder()),!this.orderId)throw new Jr;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 ca(e)&&"offsite_redirect"===(null===(t=e.body.additional_action_required)||void 0===t?void 0:t.type)}(e)){const t=null===(n=null===(i=e.body.additional_action_required)||void 0===i?void 0:i.data)||void 0===n?void 0:n.redirect_url;return new Promise(()=>window.location.replace(t))}return this.isProviderError(e)&&(yield this.paypalCommerceIntegrationService.loadPayPalSdk(r.methodId),yield new Promise((e,t)=>{var i;this.paypalcommerce&&(null===(i=this.paypalButton)||void 0===i||i.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 vd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}prepareVaultedInstrumentPaymentPayload(e,t,i){const{instrumentId:n,shouldSetAsDefaultInstrument:r}=i,o=!this.isTrustedVaultingFlow(i);return o?{methodId:e,paymentData:{shouldSaveInstrument:o,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}:{methodId:e,paymentData:{instrumentId:n,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t},bigpay_token:{token:n}}}}}preparePaymentPayload(e,t,i){const{shouldSaveInstrument:n=!1,shouldSetAsDefaultInstrument:r=!1}=_d(i)?i:{};return{methodId:e,paymentData:{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:r,formattedPayload:{paypal_account:{order_id:t}}}}}renderButton(e,t){var i,n,r,o;const a=this.paypalCommerceIntegrationService.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 gn('Unable to initialize payment because "container" argument is not provided.');const y=Object.assign(Object.assign({},this.isPaypalCommerceAppSwitchEnabled(e)&&{appSwitchWhenAvailable:!0}),{fundingSource:a.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.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===(n=(i=this.paypalButton).hasReturned)||void 0===n?void 0:n.call(i))&&this.isPaypalCommerceAppSwitchEnabled(e)?null===(o=(r=this.paypalButton).resume)||void 0===o||o.call(r):this.paypalButton.render(l))}handleClick(e,t){return Bh(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;return null==t?void 0:t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}handleApprove({orderID:e},t){this.orderId=e,null==t||t()}handleError(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createOrder(){return Bh(this,void 0,void 0,function*(){const e=this.getFieldsValues();return this.paypalCommerceIntegrationService.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&&gd(e)){const t=this.paymentIntegrationService.getState().getInstruments(),i=null==t?void 0:t.find(t=>Wd(t)&&t.bigpayToken===e.instrumentId);return!(Wd(i)&&!i.trustedShippingAddress)}return!1}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isPayPalVaultedInstrumentPaymentData(e){return!!e&&gd(e)&&_d(e)}renderMessages(e,t,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Lh(i)};e.Messages(n).render(`#${t}`)}isProviderError(e){var t,i,n;return!!function(e){return"object"==typeof e&&null!==e&&"errors"in e}(e)&&"INSTRUMENT_DECLINED"===(null===(n=null===(i=((null===(t=null==e?void 0:e.errors)||void 0===t?void 0:t.filter(e=>e.provider_error))||[])[0])||void 0===i?void 0:i.provider_error)||void 0===n?void 0:n.code)}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}}const Uh=Rt(e=>new jh(e,ys(e),new Ga(a()),new td({containerStyles:Rh})),[{id:"paypalcommerce"}]);function qh(){return new Ga(o())}var Vh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Gh{constructor(e,t,i,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=i,this.paypalCommerceSdk=n}initialize(e){return Vh(this,void 0,void 0,function*(){const{methodId:t,paypalcommerce:i,paypalcommercecredit:n}=e||{},r=n||i;if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new gn('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.paypalCommerceSdk.getPayPalMessages(a,o.getCartOrThrow().currency.code);return this.renderMessages(t,c,e)}d?this.orderId=d:(yield this.paypalCommerceIntegrationService.loadPayPalSdk(t),this.loadingIndicatorContainer=null==l?void 0:l.split("#")[1],this.renderButton(t,r))})}execute(e,t){return Vh(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);if(!this.orderId)throw new Jr;yield this.paymentIntegrationService.submitOrder(n,t),yield this.paypalCommerceIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new vd)}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 gn('Unable to initialize payment because "container" argument is not provided.');const i=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=n.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u=[i.FUNDING.PAYLATER,i.FUNDING.CREDIT];let h=!1;u.forEach(e=>{if(h)return;const t={fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o),createOrder:()=>this.paypalCommerceIntegrationService.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=i.Buttons(t),this.paypalButton.isEligible()||e!==i.FUNDING.PAYLATER){if(!this.paypalButton.isEligible()&&e===i.FUNDING.CREDIT)throw new vn(`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 Vh(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;if(t&&"function"==typeof t)return t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}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,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"payment",style:Lh(i)};e.Messages(n).render(`#${t}`)}}const Hh=Rt(e=>new Gh(e,ys(e),new td({containerStyles:Rh}),qh()),[{id:"paypalcommercecredit"}]);var $h=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Wh{constructor(e,t,i){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=i}initialize(e){var t,i;return $h(this,void 0,void 0,function*(){const{methodId:n,paypalcommerce:r,paypalcommercevenmo:o}=e||{},a=o||r;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!a)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(n);const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n);(null===(t=s.initializationData)||void 0===t?void 0:t.orderId)?this.orderId=null===(i=s.initializationData)||void 0===i?void 0:i.orderId:(yield this.paypalCommerceIntegrationService.loadPayPalSdk(n),this.loadingIndicatorContainer=a.container.split("#")[1],this.renderButton(n,a))})}execute(e,t){return $h(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);if(!this.orderId)throw new Jr;yield this.paymentIntegrationService.submitOrder(n,t),yield this.paypalCommerceIntegrationService.submitPayment(i.methodId,this.orderId)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}renderButton(e,t){const i=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e),{paymentButtonStyles:r}=n.initializationData||{},{checkoutPaymentButtonStyles:o}=r||{},{container:a,onError:s,onRenderButton:d,onValidate:c,submitForm:l}=t,u={fundingSource:i.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=i.Buttons(u),!this.paypalButton.isEligible())throw new vn("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 $h(this,void 0,void 0,function*(){const{resolve:i,reject:n}=e;return t(()=>(this.toggleLoadingIndicator(!0),i()),n)})}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 Yh=Rt(e=>new Wh(e,ys(e),new td({styles:{backgroundColor:"black"}})),[{id:"paypalcommercevenmo"}]);var Kh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Jh{constructor(e,t,i,n){this.formPoster=e,this.paymentIntegrationService=t,this.paypalRequestSender=i,this.paypalSdkLoader=n}loadPayPalSdk(e,t,i,n){return Kh(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.paypalSdkLoader.getPayPalSDK(a,o,i,n),this.paypalSdk})}getPayPalSdkOrThrow(){if(!this.paypalSdk)throw new pn;return this.paypalSdk}createBuyNowCartOrThrow(e){return Kh(this,void 0,void 0,function*(){const t=e.getBuyNowCartRequestBody();if(!t)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new Zn}})}createOrder(e,t){return Kh(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:i},t));return n})}createOrderCardFields(e,t){return Kh(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getCartOrThrow().id,{orderId:n,setupToken:r}=yield this.paypalRequestSender.createOrder(e,Object.assign({cartId:i},t));return Object.assign({orderId:n},r?{setupToken:r}:{})})}updateOrder(e){return Kh(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getConsignmentsOrThrow()[0];try{yield this.paypalRequestSender.updateOrder(e,{availableShippingOptions:n.availableShippingOptions,cartId:i.id,selectedShippingOption:n.selectedShippingOption})}catch(e){throw new Qn}})}getOrderStatus(e,t){return Kh(this,void 0,void 0,function*(){try{const{status:i}=yield this.paypalRequestSender.getOrderStatus(e,t);return i}catch(e){throw new Qn}})}tokenizePayment(e,t){const i=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new Qi(Zi.MissingOrderId);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},i.source===kt.BuyNow&&{cart_id:i.id}))}submitPayment(e,t,i){return Kh(this,void 0,void 0,function*(){const n={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:n},i?{gatewayId:i}:{}))})}getShippingOptionOrThrow(e){const t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],i=t.availableShippingOptions||[],n=i.find(e=>e.isRecommended),r=(e?i.find(t=>t.id===e):i.find(e=>{if(t.selectedShippingOption){const i=t.selectedShippingOption.id;return e.id===i}return!1}))||n||i[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,i;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===(i=null===(t=e.phone)||void 0===t?void 0:t.phone_number)||void 0===i?void 0:i.national_number})}getShippingAddressFromOrderDetails(e){const{payer:t,purchase_units:i}=e,{address:n,name:{full_name:r}}=i[0].shipping,[o,...a]=r.split(" ");return this.getAddress({firstName:o,lastName:a.join(" "),email:t.email_address,address1:n.address_line_1,address2:n.address_line_2,city:n.admin_area_2,countryCode:n.country_code,postalCode:n.postal_code,stateOrProvinceCode:n.admin_area_1})}getValidButtonStyle(e={}){const{color:t,height:i,label:n,shape:r}=e,o={color:t&&ks[t]?t:void 0,height:this.getValidHeight(i),label:n&&Ts[n]?n:void 0,shape:r&&Ds[r]?r:void 0};return H(o,k)}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 Zh=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Xh{constructor(e){this.requestSender=e}createOrder(e,t){return Zh(this,void 0,void 0,function*(){const i=`/api/storefront/payment/${e}`,n=t,r=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.post(i,{headers:r,body:n})).body})}updateOrder(e,t){return Zh(this,void 0,void 0,function*(){const i=`/api/storefront/initialization/${e}`,n=t,r=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.put(i,{headers:r,body:n})).body})}getOrderStatus(e,t){return Zh(this,void 0,void 0,function*(){const i=`/api/storefront/initialization/${e}`,n=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return(yield this.requestSender.get(i,Object.assign({headers:n},t))).body})}}const Qh=e=>{const{getHost:t}=e.getState();return new Jh(Ee(),e,new Xh(i({host:t()})),Rs())};var ep=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class tp{constructor(e,t,i,n,r=3e3,o=3e5){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalSdkScriptLoader=i,this.loadingIndicator=n,this.pollingInterval=r,this.maxPollingIntervalTime=o,this.pollingTimer=0,this.stopPolling=V,this.isPollingEnabled=!1}initialize(e){return ep(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,paypalcommerce:n,paypalcommercealternativemethods:r}=e,o=r||n;if(this.paypalcommercealternativemethods=r,!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!o)throw new gn('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');const a=this.paymentIntegrationService.getState(),s=a.getPaymentMethodOrThrow(i,t),{orderId:d,shouldRenderFields:c}=s.initializationData||{},l=a.getStoreConfigOrThrow().checkoutSettings.features;this.isPollingEnabled=Wt(l,"PAYPAL-5192.paypal_commerce_ideal_polling"),d?this.orderId=d:(this.paypalApms=yield this.paypalSdkScriptLoader.getPayPalApmsSdk(s,a.getCartOrThrow().currency.code),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(i,t,o),c&&this.renderFields(i,o))})}execute(e,t){return ep(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{methodId:r,gatewayId:o}=i;if(!this.orderId)throw new Jr;this.isPollingEnabled&&"ideal"===r&&(yield new Promise((e,t)=>{this.initializePollingMechanism(r,e,t,o)})),this.isNonInstantPaymentMethod(r)||(yield this.paymentIntegrationService.submitOrder(n,t)),yield this.paypalCommerceIntegrationService.submitPayment(r,this.orderId,o)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;return this.orderId=void 0,this.isPollingEnabled&&this.resetPollingMechanism(),null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()}initializePollingMechanism(e,t,i,n){return ep(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceIntegrationService.getOrderStatus(null!=n?n:"paypalcommerce"),o=r===ds.Approved,a=r===ds.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return i();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,paypalcommercealternativemethods:this.paypalcommercealternativemethods}),this.handleError(new rc)}catch(e){i()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}reinitializeStrategy(e){return ep(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}handleError(e){const{onError:t}=this.paypalcommercealternativemethods||{};this.isPollingEnabled&&this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}renderButton(e,t,i){const n=this.getPaypalAmpsSdkOrThrow(),r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t),{buttonStyle:o}=r.initializationData||{},{container:a,onError:s,onRenderButton:d,submitForm:c}=i,l={fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o),onInit:(e,t)=>i.onInitButton(t),createOrder:()=>this.onCreateOrder(e,t,i),onApprove:e=>this.handleApprove(e,c),onCancel:()=>{this.toggleLoadingIndicator(!1),this.deinitializePollingMechanism()},onError:e=>{this.deinitializePollingMechanism(),this.handleFailure(e,s)},onClick:(e,t)=>ep(this,void 0,void 0,function*(){return i.onValidate(t.resolve,t.reject)})};this.paypalButton=n.Buttons(l),this.paypalButton.isEligible()&&(d&&"function"==typeof d&&d(),this.paypalButton.render(a))}onCreateOrder(e,t,i){return ep(this,void 0,void 0,function*(){const{onValidate:n}=i;yield n(()=>(this.toggleLoadingIndicator(!0),()=>Promise.resolve()),V);const r=yield this.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethodscheckout");if(this.isNonInstantPaymentMethod(e)){const i={useStoreCredit:!1},n={params:{methodId:e,gatewayId:t}};yield this.paymentIntegrationService.submitOrder(i,n),yield this.paypalCommerceIntegrationService.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 i=this.getPaypalAmpsSdkOrThrow(),n=this.paymentIntegrationService.getState(),{firstName:r,lastName:o,email:a}=n.getBillingAddressOrThrow(),{apmFieldsContainer:s,apmFieldsStyles:d}=t;if(!s)throw new gn('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}}};i.PaymentFields(l).render(s)}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}isNonInstantPaymentMethod(e){return e.toUpperCase()in ss}getPaypalAmpsSdkOrThrow(){if(!this.paypalApms)throw new pn;return this.paypalApms}}const ip=Rt(e=>new tp(e,Qh(e),Rs(),new td({containerStyles:Rh})),[{gateway:"paypalcommercealternativemethods"}]);var np=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class rp{constructor(e,t,i,n){this.paymentIntegrationService=e,this.paypalIntegrationService=t,this.paypalSdkScriptLoader=i,this.paypalFastlaneUtils=n}initialize(e){return np(this,void 0,void 0,function*(){const{methodId:t,paypalcommercecreditcards:i,paypalcommerce:n}=e,r=i||n,{form:o,onCreditCardFieldsRenderingError:a,onLoadComplete:s}=r||{};if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new gn('Unable to proceed because "options.paypalcommercecreditcards.form" argument is not provided.');this.hostedFormOptions=o,this.isCreditCardForm=lc(o.fields),this.isCreditCardVaultedForm=uc(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 np(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{methodId:r,paymentData:o}=i||{};if(!i||!r)throw new oo(["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(n,t),yield this.paymentIntegrationService.submitPayment(a)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e,t,i,n;return np(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===(i=this.numberField)||void 0===i?void 0:i.close(),yield null===(n=this.nameField)||void 0===n?void 0:n.close(),Promise.resolve()})}preparePaymentPayload(e,t,i,n){const{shouldSaveInstrument:r=!1,shouldSetAsDefaultInstrument:o=!1}=_d(t)?t:{},a=t&&gd(t)?t.instrumentId:void 0,s=H({verification_nonce:n,token:a},k);return{methodId:e,paymentData:{shouldSaveInstrument:r,shouldSetAsDefaultInstrument:o,instrumentId:a,formattedPayload:Object.assign(Object.assign({},n||a?{bigpay_token:s}:{}),i?{card_with_order:{order_id:i}}:{})}}}initializeFields(e,t){return np(this,void 0,void 0,function*(){const{fields:i,styles:n}=e,r=this.paypalIntegrationService.getPayPalSdkOrThrow(),o=this.getExecuteCallback(i),a=Object.assign({style:this.getInputStyles(n),onApprove:({orderID:e,vaultSetupToken:t,liabilityShift:i})=>{if(i===is.No||i===is.Unknown)throw new Error;return this.handleApprove({orderID:e,vaultSetupToken:t})},onError:()=>{throw new Kr},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 nn(Xi.PaymentNotInitialized);try{this.stylizeInputContainers(i),lc(i)&&(yield this.renderFields(i)),uc(i)&&(yield this.renderVaultedFields(i))}catch(e){"function"==typeof t&&t(e)}})}getExecuteCallback(e){return uc(e)?this.createVaultSetupTokenCallback():this.createOrderCallback()}createVaultSetupTokenCallback(){return{createVaultSetupToken:()=>np(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:()=>np(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,i,n,r;return np(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===(i=e.cardExpiry)||void 0===i?void 0:i.containerId)&&(this.expiryField=o.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiry.containerId}`)),(null===(n=e.cardName)||void 0===n?void 0:n.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,i,n;return np(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===(i=e.cardExpiryVerification)||void 0===i?void 0:i.containerId)&&(this.expiryField=r.ExpiryField(),yield this.expiryField.render(`#${e.cardExpiryVerification.containerId}`)),(null===(n=e.cardNumberVerification)||void 0===n?void 0:n.containerId)&&(this.numberField=r.NumberField({placeholder:""}),yield this.numberField.render(`#${e.cardNumberVerification.containerId}`))})}getInstrumentParams(){if(!this.executionPaymentData)return{};if(_d(this.executionPaymentData)){const{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}=this.executionPaymentData;return{shouldSaveInstrument:e,shouldSetAsDefaultInstrument:t}}if(gd(this.executionPaymentData)){const{instrumentId:e}=this.executionPaymentData;return{instrumentId:e}}return{}}getFieldTypeByEmittedField({emittedBy:e}){return{fieldType:this.mapFieldType(e)}}submitHostedForm(){return np(this,void 0,void 0,function*(){const e=this.getCardFieldsOrThrow(),t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i={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(i)}catch(e){throw new Kr("Failed authentication. Please try to authorize again.")}})}validateHostedFormOrThrow(){var e,t;return np(this,void 0,void 0,function*(){const i=this.getCardFieldsOrThrow(),n=yield i.getState().then(e=>e),r=this.getValidityData(n);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 ao(this.mapValidationErrors(r.errors))})}getValidityData({fields:e}){const t=Object.assign({},e);delete t.cardNameField;const i=Object.keys(t);return{isValid:i.every(e=>{var i;return null===(i=t[e])||void 0===i?void 0:i.isValid}),errors:i.reduce((e,i)=>{var n;const r=this.mapFieldType(i);return Object.assign(Object.assign({},e),{[r]:(null===(n=t[i])||void 0===n?void 0:n.isValid)?void 0:[this.getInvalidErrorByFieldType(r)]})},{})}}getInvalidErrorByFieldType(e){switch(e){case cc.CardCode:case cc.CardCodeVerification:return{fieldType:e,message:"Invalid card code",type:"invalid_card_code"};case cc.CardNumber:case cc.CardNumberVerification:return{fieldType:e,message:"Invalid card number",type:"invalid_card_number"};case cc.CardExpiry:case cc.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(i=>{var n,r;t[i]=[{message:(null===(r=null===(n=e[i])||void 0===n?void 0:n[0])||void 0===r?void 0:r.message)||"",type:i}]}),t}mapFieldType(e){switch(e){case"name":return cc.CardName;case"cardNumberField":case"number":return this.isCreditCardForm?cc.CardNumber:cc.CardNumberVerification;case"cardExpiryField":case"expiry":return this.isCreditCardForm?cc.CardExpiry:cc.CardExpiryVerification;case"cardCvvField":case"cvv":return this.isCreditCardForm?cc.CardCode:cc.CardCodeVerification;default:throw new Error("Unexpected field type")}}getCardFieldsOrThrow(){if(!this.cardFields)throw new nn(Xi.PaymentNotInitialized);return this.cardFields}getInputStyles(e){var t,i,n;const r={"font-size":(null===(t=null==e?void 0:e.default)||void 0===t?void 0:t.fontSize)||"1rem","font-family":(null===(i=null==e?void 0:e.default)||void 0===i?void 0:i.fontFamily)||"Montserrat, Arial, Helvetica, sans-serif","font-weight":(null===(n=null==e?void 0:e.default)||void 0===n?void 0:n.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 i;null===(i=null==e?void 0:e.onValidate)||void 0===i||i.call(e,this.getValidityData(t))}onFocusHandler(e,t){var i;null===(i=null==e?void 0:e.onFocus)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onBlurHandler(e,t){var i;null===(i=null==e?void 0:e.onBlur)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}onInputSubmitRequest(e,t){var i;null===(i=null==e?void 0:e.onEnter)||void 0===i||i.call(e,this.getFieldTypeByEmittedField(t))}shouldInitializePayPalFastlane(e){var t,i;const n=this.paymentIntegrationService.getState(),r=n.getPaymentMethodOrThrow(e),o=n.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===(i=null==r?void 0:r.initializationData)||void 0===i?void 0:i.isPayPalCommerceAnalyticsV2Enabled)&&!(null==a?void 0:a.authenticationState)}initializePayPalFastlaneOrThrow(e){return np(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getPaymentMethodOrThrow(e),{initializationData:r}=n;if(!(null==r?void 0:r.connectClientToken))return;const o=yield this.paypalSdkScriptLoader.getPayPalFastlaneSdk(n,i.currency.code,i.id);yield this.paypalFastlaneUtils.initializePayPalFastlane(o,!!(null==r?void 0:r.isDeveloperModeApplicable))}catch(e){}})}}const op=Rt(e=>new rp(e,Qh(e),Rs(),js()),[{id:"paypalcommercecreditcards"}]);var ap=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class sp{constructor(e,t,i,n=3e3,r=3e5){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=i,this.pollingInterval=n,this.maxPollingIntervalTime=r,this.pollingTimer=0,this.stopPolling=V}initialize(e){return ap(this,void 0,void 0,function*(){const{gatewayId:t,methodId:i,paypalcommerceratepay:n}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.paypalcommerceratepay" argument is not provided.');const{legalTextContainer:r,container:o,loadingContainerId:a}=n;if(!o)throw new gn('Unable to initialize payment because "options.container" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.legalTextContainer" argument is not provided.');if(!a)throw new gn('Unable to initialize payment because "options.loadingContainerId" argument is not provided.');this.loadingIndicatorContainer=a;const s=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,t),{merchantId:d}=s.initializationData||{};if(!d)throw new gn("Unable to initialize payment because merchantId argument is not provided.");this.paypalcommerceratepay=n,yield this.paypalCommerceIntegrationService.loadPayPalSdk(i),this.createFraudNetScript(d,i,t),this.loadFraudnetConfig(),this.renderLegalText(r,o)})}execute(e,t){return ap(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{getFieldsValues:r}=this.paypalcommerceratepay||{};if(!i)throw new oo(["payment"]);if(!r||"function"!=typeof r)throw new gn('Unable to initialize payment because "options.getFieldsValues" argument is not provided.');this.toggleLoadingIndicator(!0);try{const e=yield this.paypalCommerceIntegrationService.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:i.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(n,t),yield this.paymentIntegrationService.submitPayment({methodId:i.methodId,paymentData:d}),yield new Promise((e,t)=>{this.initializePollingMechanism(i.methodId,e,t,i.gatewayId)})}catch(e){return this.handleError(e),new Promise((e,t)=>t())}})}finalize(){return Promise.reject(new vd)}deinitialize(){const{legalTextContainer:e}=this.paypalcommerceratepay||{},t=document.querySelectorAll('[data-id="fraudnetScript"]')[0],i=document.querySelectorAll('[data-id="fraudnetConfig"]')[0];if(this.deinitializePollingMechanism(),t.remove(),i.remove(),e){const t=document.getElementById(e);null==t||t.remove()}return Promise.resolve()}normalizeDate(e){const t=this.formatDate(e.getDate()),i=this.formatDate(e.getMonth()+1);return`${e.getFullYear()}-${i}-${t}`}formatDate(e){return`${e<10?0:""}${e}`}renderLegalText(e,t){const i=e,n=t.split("#")[1],r=document.getElementById(n),o=null==r?void 0:r.parentNode,a=document.createElement("div");a.style.marginBottom="20px",a.setAttribute("id",i),null==o||o.prepend(a);const s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),d=s.Legal({fundingSource:s.Legal.FUNDING.PAY_UPON_INVOICE});if(!document.getElementById(i))throw new gn('Unable to initialize payment because "legalTextContainerElement" argument is not found.');d.render(`#${i}`)}handleError(e){const{onError:t}=this.paypalcommerceratepay||{};this.resetPollingMechanism(),this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)}createFraudNetScript(e,t,i){const n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t,i),{testMode:r}=n.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 ap(this,void 0,void 0,function*(){yield this.deinitialize(),yield this.initialize(e)})}initializePollingMechanism(e,t,i,n){return ap(this,void 0,void 0,function*(){yield new Promise((e,t)=>{const i=setTimeout(e,this.pollingInterval);this.stopPolling=()=>(clearTimeout(i),this.toggleLoadingIndicator(!1),t())});try{this.pollingTimer+=this.pollingInterval;const r=yield this.paypalCommerceIntegrationService.getOrderStatus("paypalcommercealternativemethods",{params:{useMetadata:!0}}),o=r===ds.PollingStop,a=r===ds.PollingError;if(o)return this.deinitializePollingMechanism(),t();if(a)return i();if(!o&&this.pollingTimer<this.maxPollingIntervalTime)return yield this.initializePollingMechanism(e,t,i,n);yield this.reinitializeStrategy({methodId:e,gatewayId:n,paypalcommerceratepay:this.paypalcommerceratepay}),this.handleError(new rc)}catch(e){this.handleError(e),i()}})}deinitializePollingMechanism(){this.stopPolling(),this.pollingTimer=0}resetPollingMechanism(){this.deinitializePollingMechanism()}toggleLoadingIndicator(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()}}const dp=Rt(e=>new sp(e,ys(e),new td({containerStyles:Object.assign(Object.assign({},Rh),{position:"fixed"})})),[{gateway:"paypalcommercealternativemethods",id:"ratepay"}]);function cp(e){return!!e&&("authenticationState"in e||"addresses"in e||"instruments"in e)}var lp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class up{constructor(e,t,i,n){this.paymentIntegrationService=e,this.paypalCommerceRequestSender=t,this.paypalSdkScriptLoader=i,this.paypalFastlaneUtils=n}initialize(e){var t,i;return lp(this,void 0,void 0,function*(){const{methodId:n,paypalcommercefastlane:r}=e;if(this.methodId=n,this.paypalcommercefastlane=r,!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.paypalcommercefastlane" argument is not provided.');if(!r.onInit||"function"!=typeof r.onInit)throw new gn('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 gn('Unable to initialize payment because "options.paypalcommercefastlane.onChange" argument is not provided or it is not a function.');yield this.paymentIntegrationService.loadPaymentMethod(n);const o=this.paymentIntegrationService.getState(),a=o.getCartOrThrow(),s=o.getPaymentMethodOrThrow(n),{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);const l=qs(c?null===(i=null==s?void 0:s.initializationData)||void 0===i?void 0:i.fastlaneStyles:{},null==r?void 0:r.styles);yield this.paypalFastlaneUtils.initializePayPalFastlane(this.paypalFastlaneSdk,!!d,l),this.shouldRunAuthenticationFlow()&&(yield this.runPayPalAuthenticationFlowOrThrow(n)),yield this.initializePayPalPaymentComponent(),r.onInit(e=>this.renderPayPalPaymentComponent(e)),r.onChange(()=>this.handlePayPalStoredInstrumentChange(n))})}execute(e,t){return lp(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{paymentData:r,methodId:o}=i,a=r&&gd(r);try{yield this.paymentIntegrationService.submitOrder(n,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 vd)}deinitialize(){return lp(this,void 0,void 0,function*(){return Promise.resolve()})}shouldRunAuthenticationFlow(){const e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getCustomerOrThrow(),n=e.getPaymentProviderCustomer(),r=cp(n)?n:{},o=this.paypalFastlaneUtils.getStorageSessionId();return!(!i.isGuest||(null==r?void 0:r.authenticationState)===Ms.CANCELED||(null==r?void 0:r.authenticationState)||o!==t.id)}runPayPalAuthenticationFlowOrThrow(e){return lp(this,void 0,void 0,function*(){try{const t=this.paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getCustomer(),r=t.getBillingAddress(),o=(null==n?void 0:n.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===Ms.CANCELED?this.paypalFastlaneUtils.removeStorageSessionId():this.paypalFastlaneUtils.updateStorageSessionId(i.id)}catch(e){}})}initializePayPalPaymentComponent(){return lp(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),t=e.phone,i=`${e.firstName} ${e.lastName}`.trim(),n=this.paypalFastlaneUtils.getPayPalFastlaneOrThrow(),r={fields:Object.assign({cardholderName:{prefill:i,enabled:!0}},t&&{phoneNumber:{prefill:t}})};this.paypalComponentMethods=yield n.FastlaneCardComponent(r)})}renderPayPalPaymentComponent(e){const t=this.getPayPalComponentMethodsOrThrow();if(!e)throw new gn('Unable to render card component because "container" argument is not provided.');t.render(e)}getPayPalComponentMethodsOrThrow(){if(!this.paypalComponentMethods)throw new pn;return this.paypalComponentMethods}prepareVaultedInstrumentPaymentPayload(e,t){return lp(this,void 0,void 0,function*(){const{instrumentId:i}=t,n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).config.is3dsEnabled?yield this.get3DSNonce(i):i;return yield this.createOrder(n),{methodId:e,paymentData:{formattedPayload:{paypal_fastlane_token:{order_id:this.orderId,token:n}}}}})}preparePaymentPayload(e,t){return lp(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getBillingAddressOrThrow(),r=i.getPaymentMethodOrThrow(e),o=`${n.firstName} ${n.lastName}`.trim(),{getPaymentToken:a}=this.getPayPalComponentMethodsOrThrow(),{id:s}=yield a({name:{fullName:o},billingAddress:this.paypalFastlaneUtils.mapBcToPayPalAddress(n)}),d=r.config.is3dsEnabled?yield this.get3DSNonce(s):s;yield this.createOrder(d);const{shouldSaveInstrument:c=!1,shouldSetAsDefaultInstrument:l=!1}=_d(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 lp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getCartOrThrow().id;if(this.methodId){const{orderId:i}=yield this.paypalCommerceRequestSender.createOrder(this.methodId,{cartId:t,fastlaneToken:e});this.orderId=i}})}get3DSNonce(e){var t;return lp(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState(),n=i.getCartOrThrow(),r=i.getOrderOrThrow(),o=i.getStoreConfigOrThrow().links.checkoutLink,a=null===(t=this.paypalFastlaneSdk)||void 0===t?void 0:t.ThreeDomainSecureClient;if(!a)throw new pn;const s={amount:r.orderAmount.toFixed(2),currency:n.currency.code,nonce:e,threeDSRequested:this.threeDSVerificationMethod===Os.Always,transactionContext:{experience_context:{locale:"en-US",return_url:o,cancel_url:o}}},d=yield a.isEligible(s);if(this.threeDSVerificationMethod===Os.Always&&!d)throw new Jr;if(d){const{liabilityShift:e,authenticationState:t,nonce:i}=yield a.show();if(e===is.No||e===is.Unknown||t===Es.Errored||t===Es.Cancelled)throw new Jr;if(t===Es.Succeeded&&[is.Yes,is.Possible].includes(e))return i}return e})}handlePayPalStoredInstrumentChange(e){return lp(this,void 0,void 0,function*(){const t=this.paypalFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:i,selectedCard:n}=yield t.profile.showCardSelector();if(i){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomer(),i=cp(t)?t:{},r=this.paypalFastlaneUtils.mapPayPalToBcInstrument(e,n)[0];return yield this.paymentIntegrationService.updatePaymentProviderCustomer(Object.assign(Object.assign({},i),{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 hp=Rt(e=>{const{getHost:t}=e.getState();return new up(e,new hs(i({host:t()})),Rs(),js())},[{id:"paypalcommerceacceleratedcheckout"}]);var pp,mp,yp,gp,vp,fp;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(pp||(pp={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(mp||(mp={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(yp||(yp={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(gp||(gp={})),function(e){e.PILL="pill",e.RECT="rect"}(vp||(vp={})),function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(fp||(fp={}));var Sp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class wp{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t,this.useRedirectFlow=!1,this.window=window}initialize(e){return Sp(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 i=this.paymentMethod.config.merchantId;if(!this.isInContextEnabled()||!i)throw new Qi(Zi.MissingPaymentMethod);const n=yield this.scriptLoader.loadPaypalSDK();this.paypalSdk=n,this.paypalSdk.checkout.setup(i,{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 Sp(this,void 0,void 0,function*(){let i,n;const r=this.paypalSdk;if(!this.isAcknowledgedOrFinalized()){if(!this.isInContextEnabled()||this.useRedirectFlow)return i=yield this.paymentIntegrationService.submitOrder(e,t),n=i.getPaymentRedirectUrl(),n&&this.window.top&&(this.window.top.location.href=n),new Promise(V);if(!r)throw new nn(Xi.PaymentNotInitialized);r.checkout.initXO();try{i=yield this.paymentIntegrationService.submitOrder(e,t)}catch(e){return r.checkout.closeFlow(),Promise.reject(e)}return n=i.getPaymentRedirectUrl(),n&&r.checkout.startFlow(n),new Promise(V)}yield this.paymentIntegrationService.submitOrder(e,t)})}finalize(e){return Sp(this,void 0,void 0,function*(){return this.paymentIntegrationService.getState().getOrder()&&this.isAcknowledgedOrFinalized()?(yield this.paymentIntegrationService.finalizeOrder(e),Promise.resolve()):Promise.reject(new vd)})}isAcknowledgedOrFinalized(){const e=this.paymentIntegrationService.getState();return e.getPaymentStatus()===fp.ACKNOWLEDGE||e.getPaymentStatus()===fp.FINALIZE}isInContextEnabled(){return!(!this.paymentMethod||!this.paymentMethod.config.merchantId)}}class Ip{constructor(e){this.scriptLoader=e,this.window=window}loadPaypalSDK(e=""){return t=this,i=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 pn;return this.window.paypal},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}const _p=Rt(e=>new wp(e,new Ip(a())),[{id:"paypalexpress",type:"PAYMENT_TYPE_HOSTED"},{id:"paypalexpresscredit",type:"PAYMENT_TYPE_HOSTED"}]);var Cp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class bp extends Rl{constructor(e,t){super(e),this.paymentIntegrationService=e,this.threeDSecureFlow=t}initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return Cp(this,void 0,void 0,function*(){yield t.initialize.call(this,e);const i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);i.config.is3dsEnabled&&(yield this.threeDSecureFlow.prepare(i))})}execute(e,t){const i=Object.create(null,{execute:{get:()=>super.execute}});return Cp(this,void 0,void 0,function*(){const{payment:{methodId:n=""}={}}=e,r=this.paymentIntegrationService.getState();return r.getPaymentStatus()===Gc.ACKNOWLEDGE?(yield this.paymentIntegrationService.submitOrder(Object.assign(Object.assign({},e),{payment:{methodId:n}}),t),Promise.resolve()):r.getPaymentMethodOrThrow(n).config.is3dsEnabled?this.threeDSecureFlow.start(i.execute.bind(this),e,t,this._hostedForm):i.execute.call(this,e,t)})}}const Pp=Rt(e=>new bp(e,new lu(e,new Su(new wu(a())))),[{id:"paypal"}]);class Op extends Rl{constructor(e,t){super(e),this.paymentIntegrationService=e,this._formPoster=t}execute(e,t){const{payment:i}=e;if(!i)throw new nn(Xi.PaymentNotInitialized);const{paymentData:n}=i;if(!n)throw new Qi(Zi.MissingPayment);if(this._isThreeDSTwoExperimentOn()){const t=Object.assign(Object.assign({},n),{browser_info:Xa()});e.payment&&(e.payment.paymentData=t)}return super.execute(e,t).catch(e=>ca(e)&&Z(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()===Gc.FINALIZE&&this.paymentIntegrationService.finalizeOrder(e),super.finalize()}_isThreeDSTwoExperimentOn(){return!0===this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings.features["INT-4994.Opayo_3DS2"]}}const Ep=Rt(e=>new Op(e,Ee()),[{id:"sagepay"}]);class Ap extends Tu{redirectUrl(e){window.location.replace(e)}}const Tp=Rt(e=>new Ap(Ee(),e),[{id:"sezzle"}]);var kp;!function(e){e.CHARGE="CHARGE",e.STORE="STORE"}(kp||(kp={}));var Dp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Mp{constructor(e,t){this._scriptLoader=e,this._paymentIntegrationService=t}initialize({testMode:e,applicationId:t,locationId:i}){return Dp(this,void 0,void 0,function*(){const n=yield this._scriptLoader.load(e);this._payments=n.payments(t,i)})}deinitialize(){return Dp(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:i}){return Dp(this,void 0,void 0,function*(){const{postalCode:n}=this._paymentIntegrationService.getState().getBillingAddress()||{};this._card=yield this._getPayments().card(),yield this._card.attach(`#${e}`);try{yield this._card.configure({postalCode:n,style:t})}catch(e){}i&&(this._formValidationSubscription=this._subscribeToFormValidation(this._card,i))})}tokenize(){return Dp(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 rh("payment.errors.card_error","SquareV2TokenizationError",t)}return e.token})}verifyBuyer(e,t){return Dp(this,void 0,void 0,function*(){return t===kp.CHARGE?this._chargeVerifyBuyer(e):this._storeVerifyBuyer(e)})}_getPayments(){return tn(this._payments,()=>new nn(Xi.PaymentNotInitialized))}_subscribeToFormValidation(e,t){const i=["cardNumber","cvv"],n=new Set(i),r=["focusClassAdded","focusClassRemoved","errorClassAdded","errorClassRemoved","cardBrandChanged","postalCodeChanged"].map(t=>ue(e,t));return he(...r).pipe(we(e=>{const{detail:{field:t,currentState:{isCompletelyValid:r}}}=e;return i.includes(t)&&n[r?"delete":"add"](t),0===n.size}),fe()).subscribe(t)}_getCard(){return tn(this._card,()=>new nn(Xi.PaymentNotInitialized))}_mapToSquareBillingContact({firstName:e,lastName:t,address1:i,address2:n,city:r,stateOrProvinceCode:o,postalCode:a,countryCode:s,email:d,phone:c}){return{givenName:e,familyName:t,addressLines:[i,n],city:r,state:o,postalCode:a,countryCode:s,email:d,phone:c}}_chargeVerifyBuyer(e){return Dp(this,void 0,void 0,function*(){const{getCheckoutOrThrow:t,getBillingAddressOrThrow:i}=this._paymentIntegrationService.getState(),{outstandingBalance:n,cart:r}=t(),o={amount:n.toString(),billingContact:this._mapToSquareBillingContact(i()),currencyCode:r.currency.code,intent:kp.CHARGE},a=yield this._getPayments().verifyBuyer(e,o);return a?a.token:""})}_storeVerifyBuyer(e){return Dp(this,void 0,void 0,function*(){const{getBillingAddressOrThrow:t}=this._paymentIntegrationService.getState(),i={billingContact:this._mapToSquareBillingContact(t()),intent:kp.STORE},n=yield this._getPayments().verifyBuyer(e,i);return n?n.token:""})}}var zp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Np{constructor(e,t){this._paymentIntegrationService=e,this._squareV2PaymentProcessor=t}initialize(e){var t;return zp(this,void 0,void 0,function*(){if(!(null===(t=null==e?void 0:e.squarev2)||void 0===t?void 0:t.containerId))throw new gn('Unable to proceed because "containerId" argument is not provided.');const{methodId:i,squarev2:n}=e,{config:{testMode:r},initializationData:o}=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{applicationId:a,locationId:s}=o||{};if(!a)throw new Jr;yield this._squareV2PaymentProcessor.initialize({applicationId:a,locationId:s,testMode:r}),yield this._squareV2PaymentProcessor.initializeCard(n)})}execute({payment:e}){return zp(this,void 0,void 0,function*(){if(!e)throw new oo(["payment"]);const{methodId:t,paymentData:i}=e,{shouldSaveInstrument:n,shouldSetAsDefaultInstrument:r}=_d(i)?i:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1};yield this._paymentIntegrationService.submitOrder();const o=i&&gd(i)?yield this._getVaultedInstrumentPayload(t,i):yield this._getCardPayload(t,n);yield this._paymentIntegrationService.submitPayment(Object.assign(Object.assign({},e),{paymentData:{formattedPayload:Object.assign(Object.assign({},o),{vault_payment_instrument:n||!1,set_as_default_stored_instrument:r||!1})}}))})}finalize(){return Promise.reject(new vd)}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 zp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:i}=this._paymentIntegrationService.getState(),{initializationData:n}=i(e),r=yield this._squareV2PaymentProcessor.tokenize();if(n&&"isSquareV2ApiV2Enabled"in n?!n.isSquareV2ApiV2Enabled:!this.shouldVerify())return{credit_card_token:{token:r}};let o={nonce:r,token:yield this._squareV2PaymentProcessor.verifyBuyer(r,kp.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,kp.STORE)})}return{credit_card_token:{token:JSON.stringify(o)}}})}_getVaultedInstrumentPayload(e,t){return zp(this,void 0,void 0,function*(){const{getPaymentMethodOrThrow:i}=this._paymentIntegrationService.getState(),{initializationData:n}=i(e),{instrumentId:r}=t,o=(n&&"isSquareV2ApiV2Enabled"in n?n.isSquareV2ApiV2Enabled:this.shouldVerify())?yield this._squareV2PaymentProcessor.verifyBuyer(yield this._getSquareCardIdOrThrow(e,r),kp.CHARGE):void 0;return{bigpay_token:Object.assign({token:r},o&&{three_d_secure:{token:o}})}})}_getSquareCardIdOrThrow(e,t){return zp(this,void 0,void 0,function*(){const i=yield this._paymentIntegrationService.loadPaymentMethod(e,{params:{method:e,bigpayToken:t}}),{initializationData:n}=i.getPaymentMethodOrThrow(e),{cardId:r}=n||{};if(!r)throw new oo(["cardId"]);return r})}}var xp;!function(e){e.LIVE="https://web.squarecdn.com/v1/square.js",e.SANDBOX="https://sandbox.web.squarecdn.com/v1/square.js"}(xp||(xp={}));class Fp{constructor(e){this._scriptLoader=e}load(e=!1){return t=this,i=void 0,r=function*(){return yield this._scriptLoader.loadScript(e?xp.SANDBOX:xp.LIVE),function(e){if(!function(e){return"Square"in e}(e))throw new pn}(window),window.Square},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}const Rp=Rt(e=>new Np(e,new Mp(new Fp(a()),e)),[{id:"squarev2"}]);function Lp(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 Bp,jp,Up,qp;!function(e){e.Solid="solid",e.Default="default"}(Bp||(Bp={})),function(e){e.Alipay="alipay",e.CardCvc="cardCvc",e.CardExpiry="cardExpiry",e.CardNumber="cardNumber",e.CreditCard="card",e.IDEAL="idealBank",e.Sepa="iban"}(jp||(jp={})),function(e){e.Alipay="alipay",e.CreditCard="card",e.IDEAL="ideal",e.Sepa="sepa_debit"}(Up||(Up={})),function(e){e.AuthFailure="auth_failure"}(qp||(qp={}));class Vp extends Ji{constructor(e){super(e===qp.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 Gp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};const Hp=[jp.Alipay,jp.IDEAL];class $p{constructor(e,t){this.paymentIntegrationService=e,this.scriptLoader=t}initialize(e){return Gp(this,void 0,void 0,function*(){const{stripev3:t,methodId:i,gatewayId:n}=e;if(!n)throw new gn('Unable to initialize payment because "gatewayId" argument is not provided.');this.initializeOptions=t,this.isDeinitialize=!1;const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i),{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(i)&&this.shouldShowTSVHostedForm(i,n)&&c?this.hostedForm=yield this.mountCardVerificationFields(c):this.stripeElement=yield this.mountCardFields(i)})}execute(e,t){var i,n;return Gp(this,void 0,void 0,function*(){const{payment:r}=e,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);let a,s;if(!r||!r.paymentData)throw new oo(["payment.paymentData"]);const{paymentData:d,gatewayId:c,methodId:l}=r,{shouldSaveInstrument:u,shouldSetAsDefaultInstrument:h}=_d(d)?d:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},p=P(Hp,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(gd(d)){yield this.paymentIntegrationService.submitOrder(o,t);const{instrumentId:i}=d,n=e.getPaymentMethodOrThrow(r.methodId).clientToken;if(!n)throw new Qi(Zi.MissingPaymentMethod);return yield this.executeWithVaulted(r,i,h,n)}const m=e.getPaymentMethodOrThrow(l),y=yield this.confirmStripePayment(m),{clientToken:g,method:v}=m,{id:f}=null!==(n=null!==(i=y.paymentIntent)&&void 0!==i?i:y.paymentMethod)&&void 0!==n?n:{id:""};s=y.error,a={credit_card_token:{token:f},vault_payment_instrument:u,confirm:!1,set_as_default_stored_instrument:h},v===jp.CreditCard&&(a.client_token=g),p||(yield this.paymentIntegrationService.submitOrder(o,t));const S=this.buildPaymentPayload(l,a,h);yield this.paymentIntegrationService.submitPayment(S)}catch(e){yield this.processAdditionalAction(this.handleEmptyPaymentIntentError(e,s),l,u,h)}})}finalize(){return Promise.reject(new vd)}deinitialize(){return this.hostedForm&&this.hostedForm.detach(),this.isDeinitialize=!0,this.unmountElement(),Promise.resolve()}buildPaymentPayload(e,t,i){return{methodId:e,paymentData:i?{formattedPayload:Object.assign(Object.assign({},t),{set_as_default_stored_instrument:i})}:{formattedPayload:t}}}isCancellationError(e){var t,i;return e&&-1!==(null===(i=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===i?void 0:i.indexOf("canceled"))}isAuthError(e){return"payment_intent_authentication_failure"===(null==e?void 0:e.code)}isCreditCard(e){return e===Up.CreditCard}isHostedFieldAvailable(){var e;const t=this.getInitializeOptions(),i=H(null===(e=t.form)||void 0===e?void 0:e.fields,E);return!E(i)}isHostedPaymentFormEnabled(e,t){const{getPaymentMethodOrThrow:i}=this.paymentIntegrationService.getState(),n=i(e,t);return Boolean(n.config.isHostedFormEnabled)}confirmStripePayment(e){return Gp(this,void 0,void 0,function*(){const{clientToken:t,method:i,returnUrl:n}=e;if(!t)throw new Qi(Zi.MissingPaymentMethod);switch(i){case jp.Alipay:return this.getStripeJs().confirmAlipayPayment(t,{return_url:n},{handleActions:!1});case jp.IDEAL:{const e=this.mapStripePaymentData(Up.IDEAL,n);return this.getStripeJs().confirmIdealPayment(t,e,{handleActions:!1})}case jp.Sepa:{const e=this.mapStripePaymentData(Up.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()),i=this._allowRedisplayForStoredInstruments;return this.getStripeJs().createPaymentMethod(Object.assign({type:Up.CreditCard,card:e,billing_details:t},i?{allow_redisplay:"always"}:{}))}}})}executeWithVaulted(e,t,i,n){var r;return Gp(this,void 0,void 0,function*(){const o={bigpay_token:{token:t},confirm:!0,client_token:n,set_as_default_stored_instrument:i};if(this.isHostedPaymentFormEnabled(e.methodId,e.gatewayId)&&this.hostedForm){const t=this.hostedForm;return e.paymentData&&gd(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:n})})),yield t.validate(),yield t.submit(e),this.paymentIntegrationService.loadCurrentOrder()}const a=this.buildPaymentPayload(e.methodId,o,i);return this.paymentIntegrationService.submitPayment(a)})}getInitializeOptions(){if(!this.initializeOptions)throw new nn(Xi.PaymentNotInitialized);return this.initializeOptions}getStripeCardElements(){if(!this.stripeCardElements)throw new nn(Xi.PaymentNotInitialized);return this.stripeCardElements}getStripeElement(){if(!this.stripeElement)throw new nn(Xi.PaymentNotInitialized);return this.stripeElement}getStripeJs(){if(!this.stripeV3Client)throw new nn(Xi.PaymentNotInitialized);return this.stripeV3Client}handleEmptyPaymentIntentError(e,t){return ca(e)&&Z(e.body.errors,{code:"required_field"})&&t?new Error(t.message):e}loadStripeJs(e,t){return Gp(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:i,address1:n,address2:r,postalCode:o,stateOrProvinceCode:a}=e;return{city:t,country:i,line1:n,line2:r,postal_code:o,state:a}}return{line1:""}}mapStripeBillingDetails(e,t){const{firstName:i,lastName:n}=e||t||{firstName:"Guest",lastName:""},r=`${i} ${n}`.trim(),{options:o}=this.getInitializeOptions();if(this.useIndividualCardFields&&Lp(o)){const{zipCodeElementOptions:t}=o;if(t){const i=document.getElementById(t.containerId)?document.getElementById(t.containerId).value:"";i&&e&&(e=Object.assign(Object.assign({},e),{postalCode:i}))}}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:i}=t,{phone:n}=e;return n?Object.assign(Object.assign({},a),{email:i,name:r,phone:n}):Object.assign(Object.assign({},a),{email:i,name:r})}if(e){const{email:t,phone:i}=e;return i?Object.assign(Object.assign({},a),{email:t,name:r,phone:i}):Object.assign(Object.assign({},a),{email:t,name:r})}return Object.assign(Object.assign({},a),{name:r})}mapStripePaymentData(e,t){const i=this.paymentIntegrationService.getState().getCustomer(),n=this.paymentIntegrationService.getState().getBillingAddress(),r={payment_method:{[e]:this.getStripeElement(),billing_details:this.mapStripeBillingDetails(n,i)}};return e===Up.IDEAL?Object.assign(Object.assign({},r),{return_url:t}):r}mountCardFields(e){const{options:t,containerId:i}=this.getInitializeOptions();let n;return new Promise((r,o)=>{switch(this.stripeElements||(this.stripeElements=this.getStripeJs().elements()),e){case jp.CreditCard:if(this.useIndividualCardFields&&Lp(t)){const{cardNumberElementOptions:e,cardExpiryElementOptions:i,cardCvcElementOptions:r}=t,a=this.stripeElements.getElement(jp.CardNumber)||this.stripeElements.create(jp.CardNumber,e),s=this.stripeElements.getElement(jp.CardExpiry)||this.stripeElements.create(jp.CardExpiry,i),d=this.stripeElements.getElement(jp.CardCvc)||this.stripeElements.create(jp.CardCvc,r);this.stripeCardElements=[a,s,d],n=this.stripeCardElements[0];try{a.mount(`#${e.containerId}`),s.mount(`#${i.containerId}`),d.mount(`#${r.containerId}`)}catch(e){this.isDeinitialize||o(new gn("Unable to mount Stripe component without valid container ID."))}}else{n=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{n.mount(`#${i}`)}catch(e){this.isDeinitialize||o(new gn("Unable to mount Stripe component without valid container ID."))}}break;case jp.IDEAL:case jp.Sepa:n=this.stripeElements.getElement(e)||this.stripeElements.create(e,t);try{n.mount(`#${i}`)}catch(e){this.isDeinitialize||o(new gn("Unable to mount Stripe component without valid container ID."))}case jp.Alipay:}r(n)})}mountCardVerificationFields(e){return Gp(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getStoreConfig();if(!t)throw new Qi(Zi.MissingCheckoutConfig);const i=t.paymentSettings.bigpayBaseUrl,n=this.paymentIntegrationService.createHostedForm(i,e);return yield n.attach(),n})}processAdditionalAction(e,t,i=!1,n=!1){return Gp(this,void 0,void 0,function*(){if(!ca(e))throw e;const r=Z(e.body.errors,{code:"additional_action_required"}),o=Z(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 Vn;if(this.isAuthError(a.error))throw new Vp(qp.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:i,confirm:o},c=this.buildPaymentPayload(t,d,n);try{return yield this.paymentIntegrationService.submitPayment(c)}catch(e){throw this.handleEmptyPaymentIntentError(e,null==a?void 0:a.error)}}throw e})}getPaymentToken(e,t,i){return!e||i?t:e.id}shouldShowTSVHostedForm(e,t){return this.isHostedFieldAvailable()&&this.isHostedPaymentFormEnabled(e,t)}unmountElement(){this.stripeElement&&(this.stripeElement.unmount(),this.stripeElement=void 0)}}class Wp{constructor(e,t=window){this.scriptLoader=e,this.stripeWindow=t}load(e,t,i){return this.scriptLoader.loadScript("https://js.stripe.com/v3/").then(()=>{if(!this.stripeWindow.Stripe)throw new pn;return this.stripeWindow.Stripe(e,{stripeAccount:t,locale:i,betas:["payment_intent_beta_3","alipay_pm_beta_1"],apiVersion:"2020-03-02;alipay_beta=v1"})})}}const Yp=Rt(e=>new $p(e,new Wp(a())),[{gateway:"stripev3"}]),Kp={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 Jp(e){const[t,i]=e.replace(/_/g,"-").toLowerCase().split("-"),n=Kp[t];if(!n)return"auto";const r=i?`${t}-${i.toUpperCase()}`:t;return n.indexOf(r)>-1?r:n[0]}var Zp=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Xp{constructor(e,t,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=i}initialize(e){return Zp(this,void 0,void 0,function*(){const{stripeupe:t,methodId:i,gatewayId:n}=e;if(!(null==t?void 0:t.containerId))throw new nn(Xi.PaymentNotInitialized);if(!n)throw new gn('Unable to initialize payment because "gatewayId" argument is not provided.');return this._loadStripeElement(t,n,i).catch(e=>{var i;return null===(i=t.onError)||void 0===i?void 0:i.call(t,e)}),this.stripeIntegrationService.initCheckoutEventsSubscription(n,i,t,this._stripeElements),Promise.resolve()})}execute(e,t){return Zp(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i||!i.paymentData)throw new oo(["payment.paymentData"]);if(!this._stripeUPEClient)throw new nn(Xi.PaymentNotInitialized);const{paymentData:r,methodId:o,gatewayId:a}=i,{shouldSaveInstrument:s=!1,shouldSetAsDefaultInstrument:d=!1}=_d(r)?r:{},c=this.paymentIntegrationService.getState(),{isStoreCreditApplied:l}=c.getCheckoutOrThrow(),u=c.getPaymentProviderCustomerOrThrow(),h=(Ws(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(n,t),gd(r)){const{instrumentId:e}=r;return void(yield this._executeWithVaulted(i.methodId,e,d))}yield this._executeWithStripeConfirmation(i.methodId,!h&&s,d)})}finalize(){return Promise.reject(new vd)}deinitialize(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(Pa.PAYMENT))||void 0===t||t.unmount(),this.stripeIntegrationService.deinitialize(),this._stripeElements=void 0,this._stripeUPEClient=void 0,Promise.resolve()}_executeWithStripeConfirmation(e,t,i){return Zp(this,void 0,void 0,function*(){const n=this.paymentIntegrationService.getState(),{clientToken:r}=n.getPaymentMethodOrThrow(e),o=this._getPaymentPayload(e,r||"",t,i);try{yield this.paymentIntegrationService.submitPayment(o)}catch(n){yield this._processAdditionalActionWithStripeConfirmation(n,e,t,i)}})}_executeWithVaulted(e,t,i){var n;return Zp(this,void 0,void 0,function*(){const r=this.paymentIntegrationService.getState(),o=r.getPaymentMethodOrThrow(e),a=null===(n=r.getCart())||void 0===n?void 0:n.id;try{const n={methodId:e,paymentData:{formattedPayload:{cart_id:a,bigpay_token:{token:t},confirm:!1,client_token:o.clientToken,set_as_default_stored_instrument:i}}};return yield this.paymentIntegrationService.submitPayment(n)}catch(t){return this._processVaultedAdditionalAction(t,e,i)}})}_loadStripeElement(e,t,i){return Zp(this,void 0,void 0,function*(){const{containerId:n,style:r,render:o,initStripeElementUpdateTrigger:a}=e,s=yield this.paymentIntegrationService.loadPaymentMethod(t,{params:{method:i}}),d=s.getPaymentMethodOrThrow(i);if(!$s(d))throw new Qi(Zi.MissingPaymentMethod);const{clientToken:c,initializationData:l}=d,{shopperLanguage:u,allowRedisplayForStoredInstruments:h=!1,enableLink:p}=l;if(this._allowRedisplayForStoredInstruments=h,!c)throw new Qi(Zi.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:Jp(u),appearance:m});const{getBillingAddress:y,getShippingAddress:g}=s,{postalCode:v}=g()||y()||{},f=this._stripeElements.getElement(Pa.PAYMENT)||this._stripeElements.create(Pa.PAYMENT,Object.assign({fields:{billingDetails:{email:Ca.NEVER,address:{country:Ca.NEVER,city:Ca.NEVER,postalCode:v?Ca.NEVER:Ca.AUTO}}},wallets:{applePay:Ca.NEVER,googlePay:Ca.NEVER,link:p?Ca.AUTO:Ca.NEVER}},this._getStripeElementTerms()));this.stripeIntegrationService.mountElement(f,n),f.on(Ea.READY,()=>{o()}),f.on(Ea.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,i=!1,n=!1){return Zp(this,void 0,void 0,function*(){if(!ca(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new nn(Xi.PaymentNotInitialized);const{data:r}=e.body.additional_action_required,{token:o}=r,{paymentIntent:a}=yield this._confirmStripePaymentOrThrow(t,r),s=this._getPaymentPayload(t,(null==a?void 0:a.id)||o,i,n);try{yield this.paymentIntegrationService.submitPayment(s)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){var i,n;return Zp(this,void 0,void 0,function*(){const{token:r,redirect_url:o}=t,a=this.stripeIntegrationService.mapStripePaymentData(this._stripeElements,o,!!this._allowRedisplayForStoredInstruments);let s;try{const t=(yield this.stripeIntegrationService.isPaymentCompleted(e,this._stripeUPEClient))?yield null===(n=this._stripeUPEClient)||void 0===n?void 0:n.retrievePaymentIntent(r||""):yield null===(i=this._stripeUPEClient)||void 0===i?void 0:i.confirmPayment(a);if(s=null==t?void 0:t.error,s||!(null==t?void 0:t.paymentIntent))throw new Kr;return t}catch(e){this.stripeIntegrationService.throwStripeError(s)}})}_processVaultedAdditionalAction(e,t,i=!1){var n;return Zp(this,void 0,void 0,function*(){if(!t||!ca(e)||!Z(e.body.errors,{code:"three_d_secure_required"}))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new nn(Xi.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 Qn;const s=this._getPaymentPayload(t,a?r:null===(n=null==o?void 0:o.paymentIntent)||void 0===n?void 0:n.id,!1,i);return this.paymentIntegrationService.submitPayment(s)})}_loadStripeJs(e){return Zp(this,void 0,void 0,function*(){if(this._stripeUPEClient)return this._stripeUPEClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ba.V3,Da,Ma)})}_getPaymentPayload(e,t,i=!1,n=!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:i,set_as_default_stored_instrument:n}}}}_updateStripeElement({shouldShowTerms:e}){var t;const i=null===(t=this._stripeElements)||void 0===t?void 0:t.getElement(Pa.PAYMENT);null==i||i.update(Object.assign({},this._getStripeElementTerms(e)))}_getStripeElementTerms(e){let t=Ca.AUTO;return this._isStripeElementUpdateEnabled&&(t=e?Ca.AUTO:Ca.NEVER),{terms:{card:t}}}_updateStripeLinkStateByElementType(e){const t=this.paymentIntegrationService.getState().getPaymentProviderCustomerOrThrow(),i=e===_a.Link;!Ws(t)&&i&&this.paymentIntegrationService.updatePaymentProviderCustomer({stripeLinkAuthenticationState:i})}}const Qp=Rt(e=>{const t=new ka(a());return new Xp(e,t,new Zs(e,t))},[{gateway:"stripeupe"},{gateway:"stripeupe",id:"klarna"}]);var em=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class tm{constructor(e,t,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=i}initialize(e){var t;return em(this,void 0,void 0,function*(){const{stripeocs:i,methodId:n,gatewayId:r}=e;if(!(null==i?void 0:i.containerId))throw new nn(Xi.PaymentNotInitialized);if(!r)throw new gn('Unable to initialize payment because "gatewayId" argument is not provided.');try{yield this._initializeStripeElement(i,r,n)}catch(e){e instanceof Error&&(null===(t=i.onError)||void 0===t||t.call(i,e))}this.stripeIntegrationService.initCheckoutEventsSubscription(r,n,i,this.stripeElements)})}execute(e,t){return em(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{methodId:r,gatewayId:o}=i||{};if(!this.stripeClient)throw new nn(Xi.PaymentNotInitialized);if(!o||!r)throw new gn('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(n,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)}})}finalize(){return Promise.reject(new vd)}deinitialize(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Pa.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,i){return em(this,void 0,void 0,function*(){let n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,t);if((null==n?void 0:n.clientToken)||(n=(yield this.paymentIntegrationService.loadPaymentMethod(t,{params:{method:i}})).getPaymentMethodOrThrow(i,t)),!$s(n))throw new Qi(Zi.MissingPaymentMethod);const{clientToken:r,initializationData:o}=n,{shopperLanguage:a,customerSessionToken:s,enableLink:d}=o;if(!r)throw new Qi(Zi.MissingPaymentMethod);this.stripeClient=yield this._loadStripeJs(o);const{appearance:c,containerId:l,fonts:u,layout:h,render:p,paymentMethodSelect:m,handleClosePaymentMethod:y,togglePreloader:g}=e;this.stripeElements=yield this.scriptLoader.getElements(this.stripeClient,{clientSecret:r,customerSessionClientSecret:s,locale:Jp(a),appearance:c,fonts:u});const{getBillingAddress:v,getShippingAddress:f}=this.paymentIntegrationService.getState(),S=v(),{postalCode:w}=f()||S||{},I=this.stripeElements.getElement(Pa.PAYMENT)||this.stripeElements.create(Pa.PAYMENT,{fields:{billingDetails:{email:Ca.NEVER,address:{country:Ca.NEVER,city:Ca.NEVER,postalCode:w?Ca.NEVER:Ca.AUTO}}},wallets:{applePay:Ca.NEVER,googlePay:Ca.NEVER,link:d?Ca.AUTO:Ca.NEVER},layout:h,savePaymentMethod:{maxVisiblePaymentMethods:20},defaultValues:{billingDetails:{email:(null==S?void 0:S.email)||""}}});this.stripeIntegrationService.mountElement(I,l),I.on(Ea.LOADER_START,()=>{null==g||g(!1)}),I.on(Ea.READY,()=>{p()}),I.on(Ea.CHANGE,e=>{this._onStripeElementChange(e,t,i,m)}),null==y||y(this._collapseStripeElement.bind(this))})}_loadStripeJs(e){return em(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState(),i=this.stripeIntegrationService.getStripeJsVersion(e);return this.scriptLoader.getStripeClient(e,t.getCartLocale(),i)})}_collapseStripeElement(){var e;const t=null===(e=this.stripeElements)||void 0===e?void 0:e.getElement(Pa.PAYMENT);null==t||t.collapse()}_getPaymentPayload(e,t,i){var n;const r=(null===(n=this.paymentIntegrationService.getState().getCart())||void 0===n?void 0:n.id)||"",{card:o,us_bank_account:a}=i||{},s=this._shouldSaveInstrument(o)||this._shouldSaveInstrument(a),d=this._getTokenizedOptions(t,i);return{methodId:e,paymentData:{formattedPayload:Object.assign({cart_id:r,confirm:!1,method:this.selectedMethodId,vault_payment_instrument:s},d)}}}_processAdditionalAction(e,t){return em(this,void 0,void 0,function*(){if(!ca(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this.stripeClient||!this.stripeElements)throw new nn(Xi.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:n}=i,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(t,i),{client_secret:o,payment_method_options:a}=r||{},s=this._getPaymentPayload(t,o||n,a);try{return yield this.paymentIntegrationService.submitPayment(s)}catch(e){this.stripeIntegrationService.throwPaymentConfirmationProceedMessage()}})}_confirmStripePaymentOrThrow(e,t){var i,n;return em(this,void 0,void 0,function*(){const{token:r,redirect_url:o}=t,a=this.stripeIntegrationService.mapStripePaymentData(this.stripeElements,o);let s;try{const t=(yield this.stripeIntegrationService.isPaymentCompleted(e,this.stripeClient))?yield null===(n=this.stripeClient)||void 0===n?void 0:n.retrievePaymentIntent(r||""):yield null===(i=this.stripeClient)||void 0===i?void 0:i.confirmPayment(a);if(s=null==t?void 0:t.error,s||!(null==t?void 0:t.paymentIntent))throw new Kr;return t}catch(e){return this.stripeIntegrationService.throwStripeError(s)}})}_onStripeElementChange(e,t,i,n){(e=>"object"==typeof e&&null!==e&&"value"in e&&"collapsed"in e)(e)&&!e.collapsed&&(this.selectedMethodId=e.value.type,null==n||n(`${t}-${i}`))}_shouldSaveInstrument(e){const t=null==e?void 0:e.setup_future_usage;return t===Aa.ON_SESSION||t===Aa.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 im=Rt(e=>{const t=new ka(a());return new tm(e,t,new Zs(e,t))},[{gateway:"stripeocs",id:"optimized_checkout"}]);var nm=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class rm{constructor(e,t,i){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=i}initialize(e){var t;return nm(this,void 0,void 0,function*(){const{stripeocs:i,methodId:n,gatewayId:r}=e;if(!(null==i?void 0:i.containerId)||!r)throw new nn(Xi.PaymentNotInitialized);try{yield this._initializeStripeElement(i,r,n)}catch(e){e instanceof Error&&(null===(t=i.onError)||void 0===t||t.call(i,e))}this.stripeIntegrationService.initCheckoutEventsSubscription(r,n,i,this.stripeElements)})}execute(){return nm(this,void 0,void 0,function*(){return Promise.resolve()})}finalize(){return Promise.reject(new vd)}deinitialize(){return Promise.resolve()}_initializeStripeElement(e,t,i){return nm(this,void 0,void 0,function*(){let e=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(i,t);if((null==e?void 0:e.clientToken)||(e=(yield this.paymentIntegrationService.loadPaymentMethod(t,{params:{method:i}})).getPaymentMethodOrThrow(i,t)),!$s(e))throw new Qi(Zi.MissingPaymentMethod);const{clientToken:n,initializationData:r}=e;if(!n)throw new Qi(Zi.MissingPaymentMethod);this.stripeClient=yield this._loadStripeJs(r)})}_loadStripeJs(e){return nm(this,void 0,void 0,function*(){if(this.stripeClient)return this.stripeClient;const t=this.paymentIntegrationService.getState();return this.scriptLoader.getStripeClient(e,t.getCartLocale(),ba.CLOVER)})}}const om=Rt(e=>{const t=new ka(a());return new rm(e,t,new Zs(e,t))},[{gateway:"stripeocs",id:"checkout_session"}]);var am;!function(e){e.CARD_NUMBER="card-number",e.CVV="cvv",e.EXPIRY="expiry"}(am||(am={}));var sm=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class dm{constructor(e,t,i){this.paymentIntegrationService=e,this.tdOnlineMartScriptLoader=t,this.formPoster=i,this.tdInputs=[{id:"ccNumber",fieldType:am.CARD_NUMBER},{id:"ccCvv",fieldType:am.CVV},{id:"ccExpiry",fieldType:am.EXPIRY}]}initialize(e){return sm(this,void 0,void 0,function*(){const{methodId:t}=e;if(!t)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');this.tdOnlineMartClient=yield this.loadTDOnlineMartJs(),this.mountHostedFields(t)})}execute(e,t){return sm(this,void 0,void 0,function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);if(!i.methodId)throw new Qi(Zi.MissingPaymentMethod);const r=yield this.getPaymentPayloadOrThrow(i);yield this.paymentIntegrationService.submitOrder(n,t);try{yield this.paymentIntegrationService.submitPayment(r)}catch(e){yield this.processWithAdditionalAction(e)}})}finalize(){return Promise.reject(new vd)}deinitialize(){return this.tdOnlineMartClient=void 0,this.tdInputs.forEach(({inputElement:e})=>{null==e||e.unmount()}),Promise.resolve()}getPaymentPayloadOrThrow(e){return sm(this,void 0,void 0,function*(){const{methodId:t,paymentData:i}=e,{shouldSaveInstrument:n=!1,shouldSetAsDefaultInstrument:r=!1}=_d(i)?i:{},o={browser_info:Xa(),shouldSaveInstrument:n,shouldSetAsDefaultInstrument:r};if(_d(i)&&gd(i)&&i.instrumentId){const e=!!this.paymentIntegrationService.getState().getCartOrThrow().lineItems.digitalItems.length,n=!this.isTrustedVaultingInstrument(i.instrumentId)||e;return{methodId:t,paymentData:Object.assign(Object.assign(Object.assign({},o),{instrumentId:i.instrumentId}),n?{nonce:i.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(),i=this.getTDOnlineMartClientOrThrow();this.tdInputs.forEach(n=>{const r=`${e}-${n.id}`;document.getElementById(r)&&(n.inputElement=i.create(n.fieldType,t),n.inputElement.mount(`#${r}`))})}loadTDOnlineMartJs(){return sm(this,void 0,void 0,function*(){return this.tdOnlineMartClient?this.tdOnlineMartClient:this.tdOnlineMartScriptLoader.load()})}getTokenOrThrow(){return new Promise((e,t)=>{this.getTDOnlineMartClientOrThrow().createToken(i=>{const{error:n,token:r}=i;if(n||!r)return t(n);e(r)})})}getTDOnlineMartClientOrThrow(){if(!this.tdOnlineMartClient)throw new nn(Xi.PaymentNotInitialized);return this.tdOnlineMartClient}processWithAdditionalAction(e){return sm(this,void 0,void 0,function*(){if(!function(e){return ca(e)&&(t=e.body,D(t)&&"object"==typeof t&&"errors"in t&&"three_ds_result"in t&&O(t.errors)&&Z(t.errors,{code:"three_d_secure_required"}));var t}(e))throw e;const{three_ds_result:t}=e.body,{acs_url:i,payer_auth_request:n,merchant_data:r}=t||{};if(!i||!n||!r)throw new oo(["formUrl","threeDSSessionData","creq"]);return new Promise(e=>{this.formPoster.postForm(i,{threeDSSessionData:n,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 Qi(Zi.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(),i=null==t?void 0:t.find(t=>Wd(t)&&t.bigpayToken===e);return!(Wd(i)&&!i.trustedShippingAddress)}}class cm{constructor(e,t=window){this.scriptLoader=e,this.tdOnlineMartWindow=t}load(){return e=this,t=void 0,n=function*(){if(this.tdOnlineMartWindow.customcheckout||(yield this.scriptLoader.loadScript("https://libs.na.bambora.com/customcheckout/1/customcheckout.js")),!this.tdOnlineMartWindow.customcheckout)throw new pn;return this.tdOnlineMartWindow.customcheckout()},new((i=void 0)||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())});var e,t,i,n}}const lm=Rt(e=>new dm(e,new cm(a()),Ee()),[{id:"tdonlinemart"}]);var um=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};const hm="Payment cannot continue";let pm;class mm extends Rl{initialize(e){const t=Object.create(null,{initialize:{get:()=>super.initialize}});return um(this,void 0,void 0,function*(){if(this._initializeOptions=e&&e.worldpay,!this._initializeOptions)throw new nn(Xi.PaymentNotInitialized);return t.initialize.call(this,e)})}execute(e,t){const i=Object.create(null,{execute:{get:()=>super.execute}});return um(this,void 0,void 0,function*(){const{payment:n}=e;if(pm=this._submitAdditionalAction(),!n)throw new oo(["payment"]);try{return yield i.execute.call(this,e,t)}catch(e){return this._processAdditionalAction(e,n)}})}_processAdditionalAction(e,t){return um(this,void 0,void 0,function*(){return ca(e)&&Z(e.body.errors,{code:"additional_action_required"})?new Promise((i,n)=>{const r=e=>um(this,void 0,void 0,function*(){if(-1===e.origin.indexOf("cardinalcommerce.com"))return;if("string"!=typeof e.data||!this._isValidJsonWithSessionId(e.data))return n(new Error(hm));window.removeEventListener("message",r),o.remove();const a=JSON.parse(e.data),s=q({},t,{paymentData:{threeDSecure:{token:a.SessionId}}});try{i(yield pm(s))}catch(e){if(!ca(e)||!Z(e.body.errors,{code:"three_d_secure_required"}))return n(e);if(!this._initializeOptions)return n(new nn(Xi.PaymentNotInitialized));const{onLoad:t}=this._initializeOptions,i=this._createIframe(e.body.three_ds_result);try{t(i,()=>n(new Error("Payment was cancelled")))}catch(e){n(new Error(hm))}}});let o;window.addEventListener("message",r);try{o=this._createHiddenIframe(e.body)}catch(e){throw window.removeEventListener("message",r),new Error(hm)}}):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 i=document.createElement("form"),n="collectionForm";i.id=n,i.name="devicedata",i.method="post";const r=e.additional_action_required.data.redirect_url;i.action=r;const o=document.createElement("input");o.name="Bin",o.type="hidden",o.value=e.provider_data.source_id,i.appendChild(o);const a=document.createElement("input");a.name="JWT",a.type="hidden",a.value=e.provider_data.data,i.appendChild(a);const s=document.createElement("button");s.type="submit",s.id="btnsubmit",i.appendChild(s),navigator.userAgent.match("Firefox")?t.srcdoc=i.outerHTML:t.contentWindow.document.body.appendChild(i);const d=document.createElement("script");return d.innerHTML=`\n document.getElementById('${n}').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 i=document.createElement("input");i.name="JWT",i.type="hidden",i.value=e.payer_auth_request,t.appendChild(i);const n=document.createElement("input");n.name="MD",n.type="hidden",n.value=`merchantSessionId=${e.merchant_data}`,t.appendChild(n);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 nn(Xi.PaymentNotInitialized);const e=this._hostedForm;return t=>um(this,void 0,void 0,function*(){yield e.submit(t)})}return e=>um(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 ym=Rt(e=>new mm(e),[{id:"worldpayaccess"}]);class gm{constructor(e){this._requestSender=e}saveExternalId(e,t){return i=this,n=void 0,o=function*(){const i=`/api/storefront/payment/${e}/save-external-id`,n={headers:Object.assign({Accept:ur.JsonV1,"X-API-INTERNAL":cr},hr),body:{externalId:t,provider:e}};yield this._requestSender.post(i,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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}}class vm{constructor(e,t){this.paymentIntegrationService=e,this.storefrontPaymentRequestSender=t}initialize(){return Promise.resolve()}execute(e,t){return i=this,n=void 0,o=function*(){const{payment:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);if(!i)throw new oo(["payment"]);const{methodId:r}=i,{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 Qi(Zi.MissingPaymentMethod);const{id:c}=JSON.parse(a);if(!c)throw new Qi(Zi.MissingPaymentToken);const{isStoreCreditApplied:l}=this.paymentIntegrationService.getState().getCheckoutOrThrow();yield this.paymentIntegrationService.applyStoreCredit(l),yield this.paymentIntegrationService.initializePayment(r,{useStoreCredit:l}),yield this.paymentIntegrationService.submitOrder(n,t),yield this._prepareForReferredRegistration(r,c);try{yield this.paymentIntegrationService.submitPayment({methodId:r,paymentData:{nonce:c}})}catch(e){if(ca(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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}finalize(){return Promise.reject(new vd)}deinitialize(){return Promise.resolve()}_prepareForReferredRegistration(e,t){return this.storefrontPaymentRequestSender.saveExternalId(e,t)}}const fm=Rt(e=>{const{getHost:t}=e.getState(),n=i({host:t()}),r=new gm(n);return new vm(e,r)},[{id:"zip"},{id:"quadpay"}]);var Sm,wm;!function(e){e.LoadCountriesRequested="LOAD_COUNTRIES_REQUESTED",e.LoadCountriesSucceeded="LOAD_COUNTRIES_SUCCEEDED",e.LoadCountriesFailed="LOAD_COUNTRIES_FAILED"}(Sm||(Sm={}));class Im{constructor(e){this._countryRequestSender=e}loadCountries(e){return oe.create(t=>{t.next(l(Sm.LoadCountriesRequested)),this._countryRequestSender.loadCountries(e).then(e=>{t.next(l(Sm.LoadCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(Sm.LoadCountriesFailed,e))})})}}class _m{constructor(e,t){this._requestSender=e,this._config=t}loadCountries({timeout:e}={}){const t=Object.assign({"Accept-Language":this._config.locale},rt);return this._requestSender.get("/internalapi/v1/store/countries",{headers:t,timeout:e})}}class Cm extends Ze{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 bm extends Ze{constructor(e){super(e||"The tax provider is unavailable."),this.name="OrderTaxProviderUnavailableError",this.type="tax_provider_unavailable"}}class Pm extends Ze{constructor(e){super(e),this.name="MissingShippingMethodError",this.type="missing_shipping_method"}}class Om extends Ze{constructor(e){super(e),this.name="InvalidShippingAddressError",this.type="invalid_shipping_address"}}class Em{constructor(e){this._requestSender=e}loadOrder(e,{timeout:t}={}){const i=`/api/storefront/orders/${e}`,n=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.get(i,{params:{include:Mt(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:n,timeout:t})}submitOrder(e,{headers:t,timeout:i}={}){return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:H(Object.assign({"X-Checkout-Variant":t&&t.checkoutVariant},rt),k),timeout:i}).catch(e=>{if("tax_provider_unavailable"===e.body.type)throw new bm;if("cart_has_changed"===e.body.type)throw new Cm;if("missing_shipping_method"===e.body.type)throw new Pm(e.body.detail);if("invalid_shipping_address"===e.body.type)throw new Om(e.body.detail);if("empty_cart"===e.body.type)throw new it;throw e})}finalizeOrder(e,{timeout:t}={}){const i=`/internalapi/v1/checkout/order/${e}`;return this._requestSender.post(i,{timeout:t,headers:rt})}}class Am extends Ze{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"}(wm||(wm={}));var Tm;class km{constructor(e,t){this._orderRequestSender=e,this._checkoutValidator=t}loadOrder(e,t){return new oe(i=>{i.next(l(wm.LoadOrderRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{i.next(l(wm.LoadOrderSucceeded,e.body)),i.complete()}).catch(e=>{i.error(h(wm.LoadOrderFailed,e))})})}loadOrderPayments(e,t){return new oe(i=>{i.next(l(wm.LoadOrderPaymentsRequested)),this._orderRequestSender.loadOrder(e,t).then(e=>{i.next(l(wm.LoadOrderPaymentsSucceeded,e.body)),i.complete()}).catch(e=>{i.error(h(wm.LoadOrderPaymentsFailed,e))})})}loadCurrentOrder(e){return t=>de(()=>{const i=this._getCurrentOrderId(t.getState());if(!i)throw new Xe(We.MissingOrderId);return this.loadOrder(i,e)})}submitOrder(e,t){return i=>se(me(l(wm.SubmitOrderRequested)),de(()=>{const n=i.getState(),r=n.config.getExternalSource(),o=n.config.getVariantIdentificationToken(),a=n.checkout.getCheckout();if(!a)throw new Xe(We.MissingCheckout);if(a.shouldExecuteSpamCheck)throw new Am;return le(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(Ce(e=>se(this.loadOrder(e.body.data.order.orderId,t),me(l(wm.SubmitOrderSucceeded,e.body.data,Object.assign(Object.assign({},e.body.meta),{token:e.headers.token}))))))}).pipe(ge(e=>Je(wm.SubmitOrderFailed,e))))}finalizeOrder(e,t){return se(me(l(wm.FinalizeOrderRequested)),le(this._orderRequestSender.finalizeOrder(e,t)).pipe(Ce(i=>se(this.loadOrder(e,t),me(l(wm.FinalizeOrderSucceeded,i.body.data)))))).pipe(ge(e=>Je(wm.FinalizeOrderFailed,e)))}_getCurrentOrderId(e){const t=e.order.getOrder(),i=e.checkout.getCheckout();return t&&t.orderId||i&&i.orderId}_mapToOrderRequestBody(e,t,i,n){const{payment:r}=e,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]);return r?Object.assign(Object.assign({},o),{cartId:t,customerMessage:i,externalSource:n,payment:{paymentData:r.paymentData,name:r.methodId,gateway:r.gatewayId}}):Object.assign(Object.assign({},o),{cartId:t,customerMessage:i,externalSource:n})}}function Dm(e){const t=ke();return e.subscribe(e=>{const i=e.config.getStoreConfig();i&&t.setHost(i.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"}(Tm||(Tm={}));const Mm=e=>!!e;class zm{constructor(e){this._requestSender=e}loadPaymentMethodsById(e,t){return i=>new oe(n=>{var r;const o=null===(r=i.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);n.next(l(Tm.LoadPaymentMethodsRequested)),Promise.all(e.map(e=>{return i=this,n=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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).then(e=>{const t=e.filter(Mm);n.next(l(Tm.LoadPaymentMethodsSucceeded,t)),n.complete()}).catch(e=>{n.next(l(Tm.LoadPaymentMethodsFailed,e)),n.complete()})})}loadPaymentMethods(e){return t=>oe.create(i=>{const n=t.getState().cart.getCartOrThrow();i.next(l(Tm.LoadPaymentMethodsRequested)),this._requestSender.loadPaymentMethods(Object.assign(Object.assign({},e),{params:Object.assign(Object.assign({},null==e?void 0:e.params),{cartId:n.id})})).then(e=>{const t={deviceSessionId:e.headers["x-device-session-id"],sessionHash:e.headers["x-session-hash"]},n=e.body;i.next(l(Tm.LoadPaymentMethodsSucceeded,n,t)),i.complete()}).catch(e=>{i.error(h(Tm.LoadPaymentMethodsFailed,e))})})}loadPaymentMethod(e,t){return i=>oe.create(n=>{var r;const o=null===(r=i.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);n.next(l(Tm.LoadPaymentMethodRequested,void 0,{methodId:e})),this._requestSender.loadPaymentMethod(e,Object.assign(Object.assign({},t),{params:a})).then(t=>{n.next(l(Tm.LoadPaymentMethodSucceeded,t.body,{methodId:e})),n.complete()}).catch(t=>{n.error(h(Tm.LoadPaymentMethodFailed,t,{methodId:e}))})})}}!function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);o>3&&a&&Object.defineProperty(t,i,a)}([vt],zm.prototype,"loadPaymentMethod",null);class Nm{constructor(e){this._requestSender=e}loadPaymentMethods({timeout:e,params:t}={}){return this._requestSender.get("/api/storefront/payments",{timeout:e,headers:Object.assign({Accept:nt.JsonV1,"X-API-INTERNAL":Ct},rt),params:t})}loadPaymentMethod(e,{timeout:t,params:i}={}){const n=`/api/storefront/payments/${e}`;return this._requestSender.get(n,{timeout:t,headers:Object.assign({Accept:nt.JsonV1,"X-API-INTERNAL":Ct},rt),params:i})}}class xm extends Ze{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var Fm,Rm;!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"}(Fm||(Fm={})),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.LAYBUY="laybuy",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"}(Rm||(Rm={}));const Lm=Rm;class Bm{widgetInteraction(e,t){const i={methodId:t&&t.methodId};return se(me(l(Fm.WidgetInteractionStarted,void 0,i)),de(()=>e().then(()=>l(Fm.WidgetInteractionFinished,void 0,i)))).pipe(ge(e=>Je(Fm.WidgetInteractionFailed,e,i)))}}class jm{constructor(e,t,i,n,r,o){this._strategyRegistry=e,this._strategyRegistryV2=t,this._orderActionCreator=i,this._spamProtectionActionCreator=n,this._paymentIntegrationService=r,this._errorLogger=o,this._paymentStrategyWidgetActionCreator=new Bm}execute(e,t){const{payment:i={},useStoreCredit:n}=e,r={methodId:i.methodId};return o=>{const{checkout:a}=o.getState(),{shouldExecuteSpamCheck:s}=a.getCheckoutOrThrow();return se(s?this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(o):ce(),me(l(Fm.ExecuteRequested,void 0,r)),de(()=>{const a=o.getState();let s;if(a.payment.isPaymentDataRequired(n)){const e=a.paymentMethods.getPaymentMethod(i.methodId,i.gatewayId);if(!e)throw new Xe(We.MissingPaymentMethod);s=this._getStrategy(e)}else s=this._strategyRegistryV2.get({id:Lm.NO_PAYMENT_DATA_REQUIRED});return s.execute(e,Object.assign(Object.assign({},t),{methodId:i.methodId,gatewayId:i.gatewayId})).then(()=>l(Fm.ExecuteSucceeded,void 0,r))})).pipe(ge(e=>Je(Fm.ExecuteFailed,e,r)))}}finalize(e){const{integrations:t}=null!=e?e:{};return i=>se(me(l(Fm.FinalizeRequested)),this._loadOrderPaymentsIfNeeded(i,e),de(()=>{return n=this,r=void 0,a=function*(){const n=i.getState(),{providerId:r="",gatewayId:o=""}=n.payment.getPaymentId()||{},a=n.paymentMethods.getPaymentMethod(r,o);if(!a)throw new xm;const s=this._registerIntegrations(n,a,t);let d;try{d=this._getStrategy(a)}catch(e){throw new xm}return yield d.finalize(Object.assign(Object.assign({},e),{methodId:a.id,gatewayId:a.gateway})),s&&this._errorLogger.log(s),l(Fm.FinalizeSucceeded,void 0,{methodId:a.id})},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())});var n,r,o,a})).pipe(ge(e=>{const t=i.getState().payment.getPaymentId();return Je(Fm.FinalizeFailed,e,{methodId:t&&t.providerId})}))}initialize(e){const{methodId:t,gatewayId:i,integrations:n}=e;return r=>de(()=>{const o=r.getState(),a=o.paymentMethods.getPaymentMethod(t,i);if(!a)throw new Xe(We.MissingPaymentMethod);if(t&&o.paymentStrategies.isInitialized({methodId:t,gatewayId:i}))return ce();const s=this._registerIntegrations(o,a,n);s&&this._errorLogger.log(s);const d=this._getStrategy(a).initialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:i}));return se(me(l(Fm.InitializeRequested,void 0,{methodId:t,gatewayId:i})),d.then(()=>l(Fm.InitializeSucceeded,void 0,{methodId:t,gatewayId:i})))}).pipe(ge(e=>Je(Fm.InitializeFailed,e,{methodId:t,gatewayId:i})))}deinitialize(e){const{methodId:t,gatewayId:i}=e;return n=>de(()=>{const r=n.getState(),o=r.paymentMethods.getPaymentMethod(t,i);if(!o)throw new Xe(We.MissingPaymentMethod);if(t&&!r.paymentStrategies.isInitialized({methodId:t,gatewayId:i}))return ce();const a=this._getStrategy(o).deinitialize(Object.assign(Object.assign({},e),{methodId:t,gatewayId:i}));return se(me(l(Fm.DeinitializeRequested,void 0,{methodId:t,gatewayId:i})),a.then(()=>l(Fm.DeinitializeSucceeded,void 0,{methodId:t,gatewayId:i})))}).pipe(ge(e=>Je(Fm.DeinitializeFailed,e,{methodId:t,gatewayId:i})))}widgetInteraction(e,t){return this._paymentStrategyWidgetActionCreator.widgetInteraction(e,t)}_registerIntegrations(e,t,i){const{features:n}=e.config.getStoreConfigOrThrow().checkoutSettings,r=Wt(n,"CHECKOUT-9450.lazy_load_payment_strategies",!1);let o=!0;try{this._strategyRegistry.getByMethod(t)}catch(e){o=!1}if(r&&!o){const e={id:t.id,gateway:t.gateway,type:t.type},n=Kt(this._strategyRegistryV2,null!=i?i:[],e,this._paymentIntegrationService);return Yt(this._strategyRegistryV2,null!=i?i:[],this._paymentIntegrationService),n}}_getStrategy(e){let t;try{t=this._strategyRegistry.getByMethod(e)}catch(i){t=this._strategyRegistryV2.get({id:e.id,gateway:e.gateway,type:e.type})}return t}_loadOrderPaymentsIfNeeded(e,t){const i=e.getState().checkout.getCheckout();return i&&i.orderId?this._orderActionCreator.loadOrderPayments(i.orderId,t):ce()}}class Um{isEqual(e,t){return A(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 qm extends Ze{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 Vm{constructor(e){this._checkoutRequestSender=e}validate(e,t){if(!e)throw new Xe(We.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then(t=>{const i=new Um;if(!(e.outstandingBalance===t.body.outstandingBalance&&this._compareCoupons(e.coupons,t.body.coupons)&&this._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&i.isEqual(e.cart,t.body.cart)))throw new qm(this._getComparableCheckout(e),this._getComparableCheckout(t.body))})}_compareCoupons(e,t){return A(B(e,"code"),B(t,"code"))}_compareGiftCertificates(e,t){return A(B(e,"code"),B(t,"code"))}_getComparableCheckout(e){const{cart:t,coupons:i,giftCertificates:n,outstandingBalance:r}=e;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:i,giftCertificates:n,outstandingBalance:r}}}class Gm{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 Hm extends Ze{constructor(){super("Please complete our human verification challenge and try again."),this.name="CardingProtectionChallengeNotCompletedError",this.type="carding_protection_challenge_not_completed"}}class $m extends Ze{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 Wm,Ym,Km=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Jm{constructor(e){this._googleRecaptcha=e}handle(e,t){return Km(this,void 0,void 0,function*(){return"string"==typeof e?this.handleWithRecaptchaSitekey(e,t):this.handleWithPaymentHumanVerificationRequestError(e)})}handleWithPaymentHumanVerificationRequestError(e){return Km(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 Km(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(be(1)).pipe(Ce(({error:e,token:t})=>Km(this,void 0,void 0,function*(){if(e instanceof oi)throw new Hm;if(e||!t)throw new $m;return{type:"recaptcha_v2_verification",data:{human_verification_token:t}}}))).toPromise()}_initialize(e){const t="cardingProtectionContainer";let i=document.getElementById(t);return i&&i.parentNode&&i.parentNode.removeChild(i),i=document.createElement("div"),i.setAttribute("id",t),document.body.appendChild(i),this._googleRecaptcha.load(t,e)}_isPaymentHumanVerificationRequest(e){const{additional_action_required:t,status:i}=e.body||{};return"additional_action_required"===i&&t&&"recaptcha_v2_verification"===t.type}}function Zm(e,t){const{body:i}=e,{errors:n=[]}=i;return new It(e,{message:Xm(n)||t,errors:n})}function Xm(e){if(Array.isArray(e))return e.reduce((e,t)=>t&&t.message?[...e,t.message]:e,[]).join(" ")}class Qm extends Ze{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 ey extends Ze{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 ty extends Ze{constructor(e){super(["Unable to proceed due to invalid user input values",...I(ne(e),e=>B(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"}(Wm||(Wm={})),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"}(Ym||(Ym={}));var iy=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ny{constructor(e,t,i,n,r,o,a,s,d,c){this._type=e,this._containerId=t,this._placeholder=i,this._accessibilityLabel=n,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.864.0&checkoutId=${this._checkoutId}`:"/checkout/payment/hosted-field?version=1.864.0";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 iy(this,void 0,void 0,function*(){const e=document.getElementById(this._containerId);if(!e)throw new Qm("Unable to proceed because the provided container ID is not valid.");e.appendChild(this._iframe),this._eventListener.listen();const t=ue(this._iframe,"load").pipe(Ce(({target:e})=>iy(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:Wm.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:Ym.AttachSucceeded,errorType:Ym.AttachFailed})})),be(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 iy(this,void 0,void 0,function*(){try{const i=this._eventPoster.post({type:Wm.SubmitRequested,payload:{fields:e,data:t}},{successType:Ym.SubmitSucceeded,errorType:Ym.SubmitFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],i)}catch(e){if(this._isSubmitErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new ey(e.payload.error.message);if(e.payload.response)throw Zm(e.payload.response);throw new Error(e.payload.error.message)}throw e}})}submitStoredCardForm(e,t){return iy(this,void 0,void 0,function*(){const i=this._eventPoster.post({type:Wm.StoredCardRequested,payload:{fields:e,data:t}},{successType:Ym.StoredCardSucceeded,errorType:Ym.StoredCardFailed});return this._detachmentObserver.ensurePresence([this._iframe],i)})}validateForm(){return iy(this,void 0,void 0,function*(){const e=this._eventPoster.post({type:Wm.ValidateRequested},{successType:Ym.Validated}),{payload:t}=yield this._detachmentObserver.ensurePresence([this._iframe],e);if(!t.isValid)throw new ty(t.errors)})}_getFontUrls(){const e="fonts.googleapis.com",t=document.querySelectorAll(`link[href*='${e}'][rel='stylesheet']`);return Array.prototype.slice.call(t).filter(t=>wi(t.href).hostname===e).filter(e=>ne(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===Ym.SubmitFailed}}var ry,oy=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ay{constructor(e,t,i,n,r){this._fields=e,this._eventListener=t,this._payloadTransformer=i,this._eventCallbacks=n,this._paymentHumanVerificationHandler=r,this._handleEnter=({payload:e})=>oy(this,void 0,void 0,function*(){try{yield this.validate()}catch(e){if(e instanceof Error&&"InvalidHostedFormValueError"!==e.name)throw e}const{onEnter:t=V}=this._eventCallbacks;t(e)});const{onBlur:o=V,onCardTypeChange:a=V,onFocus:s=V,onValidate:d=V}=this._eventCallbacks;this._eventListener.addListener(Ym.Blurred,({payload:e})=>o(e)),this._eventListener.addListener(Ym.CardTypeChanged,({payload:e})=>a(e)),this._eventListener.addListener(Ym.Focused,({payload:e})=>s(e)),this._eventListener.addListener(Ym.Validated,({payload:e})=>d(e)),this._eventListener.addListener(Ym.Entered,this._handleEnter),this._eventListener.addListener(Ym.CardTypeChanged,({payload:e})=>this._cardType=e.cardType),this._eventListener.addListener(Ym.BinChanged,({payload:e})=>this._bin=e.bin)}getBin(){return this._bin}getCardType(){return this._cardType}attach(){return oy(this,void 0,void 0,function*(){this._eventListener.listen();const e=this._getFirstField(),t=re(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 oy(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 i=yield this._paymentHumanVerificationHandler.handle(t);return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),this._payloadTransformer.transform(e,i))}})}submitStoredCard(e){return oy(this,void 0,void 0,function*(){return this._getFirstField().submitStoredCardForm(e.fields,e.data)})}validate(){return oy(this,void 0,void 0,function*(){return this._getFirstField().validateForm()})}_getFirstField(){const e=this._fields[0];if(!e)throw new Qm("Unable to proceed because the payment form has no field defined.");return e}}function sy(e){return Boolean(e.instrumentId)}class dy{constructor(e){this._store=e}transform(e,t){const i=this._store.getState(),n=i.checkout.getCheckout(),r=i.config.getConfig(),o=i.instruments.getInstrumentsMeta(),a=i.order.getOrder(),s=i.order.getOrderMeta(),d=G(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv"),c=i.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),l=i.paymentMethods.getPaymentMethodsMeta(),u=o&&d&&sy(d)?`${i.payment.getPaymentToken()}, ${o.vaultAccessToken}`:i.payment.getPaymentToken();if(!u)throw new Xe(We.MissingPaymentToken);return{additionalAction:t,authToken:u,checkout:n,config:r,order:a,orderMeta:s,payment:d,paymentMethod:c,paymentMethodMeta:l}}}class cy{constructor(e){this._store=e}create(e,t,i){const n=Object.keys(t.fields).reduce((n,r)=>{const o=t.fields[r];return o?[...n,new ny(r,o.containerId,o.placeholder||"",o.accessibilityLabel||"",t.styles||{},new Ci(e),new $i(e),new Ai(new hi),i,"instrumentId"in o?this._getCardInstrument(o.instrumentId):void 0)]:n},[]);return new ay(n,new $i(e),new dy(this._store),W(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new Jm(vi(o())))}_getCardInstrument(e){const{instruments:{getCardInstrument:t}}=this._store.getState(),i=t(e);if(!i)throw new Xe(We.MissingPaymentInstrument);return i}}!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"}(ry||(ry={}));class ly{constructor(e,t,i,n){this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=i,this._paymentHumanVerificationHandler=n,this.initializeOffsitePayment=({methodId:e,gatewayId:t,instrumentId:i,target:n,promise:r,shouldSaveInstrument:o,shouldSetAsDefaultInstrument:a})=>s=>{let d;i?d={formattedPayload:{bigpay_token:i}}: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 se(me(l(ry.InitializeOffsitePaymentRequested)),Promise.race([this._paymentRequestSender.initializeOffsitePayment(c,n),r].filter(Boolean)).then(()=>l(ry.InitializeOffsitePaymentSucceeded))).pipe(ge(e=>Je(ry.InitializeOffsitePaymentFailed,e)))}}submitPayment(e){return t=>se(me(l(ry.SubmitPaymentRequested)),de(()=>{return i=this,n=void 0,o=function*(){try{return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,t.getState()))}catch(i){const n=yield this._paymentHumanVerificationHandler.handle(i);return yield this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(Object.assign(Object.assign({},e),{additionalAction:n}),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}).pipe(Ce(({body:e})=>se(this._orderActionCreator.loadCurrentOrder()(t),me(l(ry.SubmitPaymentSucceeded,e)))))).pipe(ge(e=>Je(ry.SubmitPaymentFailed,e)))}}class uy{constructor(e){this._client=e}submitPayment(e){return new Promise((t,i)=>{this._client.submitPayment(e,(e,n)=>{e?i(this._transformResponse(e)):t(this._transformResponse(n))})})}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 hy(e,t){let i;return function(e){return void 0!==e.id}(e)?i=e.id:t&&t.length&&(i=t[0].id),{id:i,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 py=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function my(e){return{code:e.code,discount:e.displayName,discountType:py.indexOf(e.couponType)}}function yy(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function gy(e){const t=[];return(e||[]).forEach(e=>{(e.banners||[]).forEach(e=>{t.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})})}),t}function vy(e,t,i="id"){return Object.keys(e).reduce((n,r)=>[...n,...e[r].map(e=>"giftCertificates"===r?function(e,t){const i=new id(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:i.toInteger(e.amount),integerAmountAfterDiscount:i.toInteger(e.amount),integerUnitPrice:i.toInteger(e.amount),integerUnitPriceAfterDiscount:i.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,i,n="id"){const r=new id(i);return{id:e[n],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,i))],[])}function fy(e){const t=e.cart.currency.decimalPlaces,i=new id(t);return{id:e.cart.id,items:vy(e.cart.lineItems,t),currency:e.cart.currency.code,coupon:{discountedAmount:K(e.cart.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.cart.coupons.map(my)},discount:{amount:e.cart.discountAmount,integerAmount:i.toInteger(e.cart.discountAmount)},discountNotifications:gy(e.promotions),giftCertificate:{totalDiscountedAmount:K(e.giftCertificates,(e,t)=>e+t.used,0),appliedGiftCertificates:F(e.giftCertificates.map(yy),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount),required:Z(e.cart.lineItems.physicalItems,e=>e.isShippingRequired)},subtotal:{amount:e.subtotal,integerAmount:i.toInteger(e.subtotal)},storeCredit:{amount:e.customer?e.customer.storeCredit:0},taxSubtotal:{amount:e.taxTotal,integerAmount:i.toInteger(e.taxTotal)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:i.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:i.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.grandTotal,integerAmount:i.toInteger(e.grandTotal)}}}var Sy;!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"}(Sy||(Sy={}));const wy=Sy;function Iy(e,t){const i=e.firstName||t.firstName||"",n=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map(e=>hy(e)),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:i,lastName:n,name:e.fullName||[i,n].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}class _y{format(e){const[t="",i=""]=e.split(new RegExp("\\s*/\\s*")),n=t.slice(0,2),r=4===i.length?i.slice(-2):i?i.slice(0,2):t.slice(2);return e.length<2?t:e.length>3&&!r?n:`${n} / ${r}`}toObject(e){const[t="",i=""]=e.split(new RegExp("\\s*/\\s*"));return/^\d+$/.test(t)&&/^\d+$/.test(i)?{month:1===t.length?`0${t}`:t.slice(0,2),year:2===i.length?`20${i}`:i.slice(0,4)}:{month:"",year:""}}}class Cy{format(e){const{card:t}=Me(e);if(!t)return e;const i=j(De(e).map(e=>j(e.lengths))),n=this.unformat(e).slice(0,i);return t.gaps.filter(e=>n.length>e).reduce((e,t,i)=>[e.slice(0,t+i),e.slice(t+i)].join(" "),n)}unformat(e){const{card:t}=Me(e);return t?e.replace(new RegExp(" ","g"),""):e}}function by(e,t={}){const i=e.currency.decimalPlaces,n=new id(i);return{id:e.orderId,items:vy(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:Ey(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:n.toInteger(e.baseAmount)},coupon:{discountedAmount:K(e.coupons,(e,t)=>e+t.discountedAmount,0),coupons:e.coupons.map(my)},discount:{amount:e.discountAmount,integerAmount:n.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:Oy(e.payments),socialData:Ty(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:n.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:n.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:Py(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:n.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:n.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function Py(e){const t=S(e,{providerId:"storecredit"});return t?t.amount:0}function Oy(e){const t=f(e,{providerId:"giftcertificate"});return{totalDiscountedAmount:K(t,(e,t)=>t.amount+e,0),appliedGiftCertificates:F(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 Ey(e,t={}){const i=S(e,Ay);return i?{id:i.providerId,status:(n=i.detail.step,`PAYMENT_STATUS_${n}`),helpText:i.detail.instructions,returnUrl:t.returnUrl}:{};var n}function Ay(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function Ty(e){const t={};return[...e.lineItems.physicalItems,...e.lineItems.digitalItems].forEach(e=>{var i;t[e.id]=(i=e,["fb","tw","gp"].reduce((e,t)=>{const n=i.socialMedia&&S(i.socialMedia,e=>e.code===t);return n?(e[t]={name:i.name,description:i.name,image:i.imageUrl,url:n.link,shareText:n.text,sharingLink:n.link,channelName:n.channel,channelCode:n.code},e):e},{}))}),t}function ky(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 Dy{constructor(){this._cardExpiryFormatter=new _y,this._cardNumberFormatter=new Cy}transform(e,t){const i=t.billingAddress.getBillingAddress(),n=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&&i&&Iy(r,i),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 Xe(We.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:g,customer:y,billingAddress:i&&hy(i),shippingAddress:s&&hy(s,d),shippingOption:c&&ky(c,!0),cart:n&&fy(n),order:o&&by(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:W(l&&l.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}}transformWithHostedFormData(e,t,i){const{additionalAction:n,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:n,authToken:r,paymentMethod:l&&this._transformPaymentMethod(l),customer:s&&s.billingAddress&&o&&Iy(o.customer,s.billingAddress),billingAddress:s&&s.billingAddress&&hy(s.billingAddress),shippingAddress:p&&o&&hy(p,o.consignments),shippingOption:m&&ky(m,!0),cart:o&&fy(o),order:s&&by(s,d),orderMeta:d,payment:this._transformHostedInputValues(e,c,i),quoteMeta:{request:Object.assign(Object.assign({},u),{geoCountryCode:a&&a.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:a&&W(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}):e.id===wy.BRAINTREE_VENMO?Object.assign(Object.assign({},e),{id:wy.BRAINTREE_PAYPAL}):e:Object.assign(Object.assign({},e),{gateway:e.id})}_transformHostedInputValues(e,t,i){return"instrumentId"in t?Object.assign(Object.assign({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:i}):Object.assign(Object.assign({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:i})}_mapShippingAddress(e,t){var i,n,r,o;if(t){const a=null===(n=null===(i=t.initializationData)||void 0===i?void 0:i.bopis)||void 0===n?void 0:n.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 My=e=>{const{type:t,initializationStrategy:i}=e;return t===Lm.PPSDK&&"string"==typeof(null==i?void 0:i.type)};class zy extends Bt{getByMethod(e){if(!e)return this.get();const t=this._getToken(e),i=[e.gateway,e.id].filter(e=>null!=e).join("-");return this.get(t,i)}_getToken(e){if(My(e))return Lm.PPSDK;if("klarna"===e.gateway)return Lm.KLARNAV2;const t=e.gateway||e.id;if(this._hasFactoryForMethod(t))return t;if("PAYMENT_TYPE_OFFLINE"===e.type)return Lm.OFFLINE;throw new Lt(`'${t}' is not registered.`)}_hasFactoryForMethod(e){return this._hasFactory(e)}}const Ny="FINALIZE";class xy extends Lt{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 Fy=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i};class Ry{constructor(e,t,i,n){this._store=e,this._orderActionCreator=t,this._paymentActionCreator=i,this._hostedFormFactory=n}execute(e,t){var i,n;return this._isHostedPaymentFormEnabled(null===(i=e.payment)||void 0===i?void 0:i.methodId,null===(n=e.payment)||void 0===n?void 0:n.gatewayId)&&this._shouldRenderHostedForm?this._executeWithHostedForm(e,t):this._executeWithoutHostedForm(e,t)}finalize(e){return Promise.reject(new xm)}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:i}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:n=""}={}}=i.getStoreConfig()||{};if(!t)throw new Lt;const r=this._hostedFormFactory.create(n,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:i}=e,n=Fy(e,["payment"]),r=i&&i.paymentData;if(!i||!r)throw new xy(["payment.paymentData"]);return this._store.dispatch(this._orderActionCreator.submitOrder(n,t)).then(()=>this._store.dispatch(this._paymentActionCreator.submitPayment(Object.assign(Object.assign({},i),{paymentData:r}))))}_executeWithHostedForm(e,t){const{payment:i}=e,n=Fy(e,["payment"]),r=this._hostedForm;if(!r)throw new pi(si.PaymentNotInitialized);if(!i||!i.methodId)throw new xy(["payment.methodId"]);return r.validate().then(()=>this._store.dispatch(this._orderActionCreator.submitOrder(n,t))).then(()=>r.submit(i)).then(()=>this._store.dispatch(this._orderActionCreator.loadCurrentOrder()))}_isHostedPaymentFormEnabled(e,t){if(!e)return!1;const{paymentMethods:{getPaymentMethodOrThrow:i}}=this._store.getState();return!0===i(e,t).config.isHostedFormEnabled}_isHostedFieldAvailable(e){return!ne(e&&e.creditCard&&e.creditCard.form.fields).every(k)}}class Ly extends Ry{constructor(e,t,i,n,r){super(e,t,i,n),this._formPoster=r}execute(e,t){return super.execute(e,t).catch(e=>e instanceof It&&Z(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(),i=t.order.getOrder();return i&&t.payment.getPaymentStatus()===Ny?this._store.dispatch(this._orderActionCreator.finalizeOrder(i.orderId,e)):Promise.reject(new xm)}}class By extends Ze{constructor(e){super(e||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}const jy="redirecting";class Uy{constructor(){this._isRedirecting=this.currentUrlHasRedirectingParam()}isRedirecting(){return this._isRedirecting}setRedirecting(e){e?this.setRedirectingParamOnUrl():this.removeRedirectingParamFromUrl(),this._isRedirecting=e}currentUrlHasRedirectingParam(){return jy in this.getCurrentUrl().query}getCurrentUrl(){return Ne(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),{[jy]:"true"})});this.replaceCurrentUrl(xe(t))}removeRedirectingParamFromUrl(){this.currentUrlHasRedirectingParam()&&this.replaceCurrentUrl(ze(window.location.href,[jy]))}}const qy=$([e=>"continue"===C(e,"type")&&"redirect"===C(e,"code")&&(e=>{const t=C(e,"form_fields");return z(C(e,"url"))&&(N(t)||D(t))})(C(e,"parameters")),e=>"continue"===C(e,"type")&&"resubmit_with_human_verification"===C(e,"code")&&(e=>{const t=C(e,"available_methods");return O(t)})(C(e,"parameters"))]);class Vy{constructor(e,t){this._formPoster=e,this._humanVerificationHandler=t}handle(e,t){switch(e.code){case"redirect":return(({url:e,form_fields:t},i)=>{const n=new Uy;return n.isRedirecting()?(n.setRedirecting(!1),Promise.reject(new By)):(n.setRedirecting(!0),t?i.postForm(e,t):window.location.assign(e),new Promise(V))})(e.parameters,this._formPoster);case"resubmit_with_human_verification":return(({available_methods:e},t,i)=>{return n=void 0,r=void 0,a=function*(){if(!i)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:n,parameters:r}=e[0],o=yield t.handle(n,r.key);return i(o)},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())});var n,r,o,a})(e.parameters,this._humanVerificationHandler,null==t?void 0:t.humanVerification)}}}class Gy{constructor(e){this._continueHandler=e}handle(e,t){const{body:i}=e;return(e=>"success"===C(e,"type"))(i)?Promise.resolve():(e=>qy(e))(i)?this._continueHandler.handle(i,null==t?void 0:t.continue):(e=>"failure"===C(e.body,"type")&&z(C(e.body,"code")))(e)?(e=>{return Promise.reject(new It((t=e,Object.assign(Object.assign({},t),{body:{errors:[{code:t.body.code}]}}))));var t})(e):((e=>{C(e.body,"type")})(e),(e=>Promise.reject(new It(e)))(e))}}const Hy="completed-payments";class $y{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(Hy)||[]}setCompletedPayments(e){this._browserStorage.setItem(Hy,e)}}var Wy,Yy=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ky{constructor(e,t,i,n,r){this._store=e,this._orderActionCreator=t,this._subStrategyRegistry=i,this._paymentResumer=n,this._completedPayments=new $y(r)}execute(e,t){var i;return Yy(this,void 0,void 0,function*(){const{bigpayBaseUrl:n}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==t?void 0:t.methodId))throw new Lt('Unable to submit payment because "options.methodId" argument is not provided.');const{methodId:r}=t,{payment:o}=e,a=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["payment"]),{_subStrategy:s}=this;if(!s)throw new pi(si.PaymentNotInitialized);yield this._store.dispatch(this._orderActionCreator.submitOrder(a,t));const d=null===(i=this._store.getState().order.getOrderMeta())||void 0===i?void 0:i.token;if(!d)throw new Xe(We.MissingOrder);return yield s.execute({methodId:r,payment:o,bigpayBaseUrl:n,token:d}),this._store.getState()})}finalize(e){return Yy(this,void 0,void 0,function*(){const t=this._store.getState().order.getOrderOrThrow();if(t.isComplete)return this._store.getState();const{bigpayBaseUrl:i}=this._store.getState().config.getStoreConfigOrThrow().paymentSettings;if(!(null==e?void 0:e.methodId))throw new Lt('Unable to submit payment because "options.methodId" argument is not provided.');const n=this._store.getState().order.getPaymentId(e.methodId);if(!n||!t||this._completedPayments.isCompleted(n))throw new xm;const{orderId:r}=t;return yield this._paymentResumer.resume({paymentId:n,bigpayBaseUrl:i,orderId:r}).catch(e=>{throw this._completedPayments.setCompleted(n),e}),this._store.getState()})}initialize(e){return Yy(this,void 0,void 0,function*(){if(!(null==e?void 0:e.methodId))throw new Lt('Unable to submit payment because "options.methodId" argument is not provided.');const t=((e,t)=>{const i=e.getState().paymentMethods.getPaymentMethod(t);if(i&&My(i))return i})(this._store,e.methodId);if(!t)throw new pi(si.PaymentNotInitialized);if(this._subStrategy=this._subStrategyRegistry.getByMethod(t),!this._subStrategy)throw new pi(si.PaymentNotInitialized);return yield this._subStrategy.initialize(e),this._store.getState()})}deinitialize(e){var t;return Yy(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"}(Wy||(Wy={}));const Jy=m([[e=>"card_ui"===e.type,y(Wy.CARD)],[e=>"none"===e.type,y(Wy.NONE)],[X,y(Wy.UNSUPPORTED)]]);class Zy extends Bt{getByMethod(e){const t=Jy(e.initializationStrategy);return this.get(t)}}var Xy=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Qy{constructor(e,t,i,n){this._store=e,this._orderActionCreator=t,this._hostedFormFactory=i,this._ppsdkStepHandler=n}execute(e){return Xy(this,void 0,void 0,function*(){const t=this._hostedForm;if(!t)throw new pi(si.PaymentNotInitialized);const{additionalAction:i,payment:n}=e;if(!n||!n.methodId)throw new xy(["payment.methodId"]);yield t.validate();const{payload:r}=yield t.submit(n,i),{response:o}=r;yield this._ppsdkStepHandler.handle(o,{continue:{humanVerification:t=>Xy(this,void 0,void 0,function*(){return this.execute(Object.assign({additionalAction:t},e))})}}),yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder())})}initialize(e){return Xy(this,void 0,void 0,function*(){const t=e&&e.creditCard&&e.creditCard.form,{config:i,checkout:n}=this._store.getState(),{paymentSettings:{bigpayBaseUrl:r=""}={}}=i.getStoreConfig()||{},o=n.getCheckoutOrThrow().id;if(!t)throw new Lt;const a=t&&this._hostedFormFactory.create(r,t,o);yield a.attach(),this._hostedForm=a})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}class eg{constructor(e,t){this._requestSender=e,this._stepHandler=t}execute({methodId:e,bigpayBaseUrl:t,token:i}){const n={credentials:!1,body:{payment_method_id:e},headers:{authorization:i,"X-XSRF-TOKEN":null}};return this._requestSender.post(`${t}/payments`,n).then(e=>this._stepHandler.handle(e))}initialize(){return Promise.resolve()}deinitialize(){}}var tg,ig,ng=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class rg{constructor(e,t){this._requestSender=e,this._stepHandler=t}resume({paymentId:e,bigpayBaseUrl:t,orderId:i}){return ng(this,void 0,void 0,function*(){const n={credentials:!1,headers:{authorization:yield this._getToken(i).catch(()=>{throw new xm}),"X-XSRF-TOKEN":null}};return this._requestSender.get(`${t}/payments/${e}`,n).then(e=>this._stepHandler.handle(e))})}_getToken(e){return ng(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 og extends Ry{constructor(e,t,i,n,r){super(e,t,i,n),this._wepayRiskClient=r}initialize(e){return this._wepayRiskClient.initialize(),super.initialize(e)}execute(e,t){const i=this._wepayRiskClient.getRiskToken(),n=q({},e,{payment:{paymentData:{deviceSessionId:i}}});return super.execute(n,t)}}class ag{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 pi(si.PaymentNotInitialized);return this._riskClient.generate_risk_token(),this._riskClient.get_risk_token()}}class sg{constructor(e){this._requestSender=e}createBuyNowCart(e,{timeout:t}={}){const i=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post("/api/storefront/carts",{body:e,headers:i,timeout:t})}}!function(e){e.UpdatePaymentProviderCustomer="UPDATE_PAYMENT_PROVIDER_CUSTOMER"}(tg||(tg={}));class dg{updatePaymentProviderCustomer(e){return me(l(tg.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"}(ig||(ig={}));var cg;class lg{constructor(e,t){this._remoteCheckoutRequestSender=e,this._checkoutActionCreator=t}initializeBilling(e,t,i){return oe.create(n=>{n.next(l(ig.InitializeRemoteBillingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeBilling(e,t,i).then(({body:t={}})=>{n.next(l(ig.InitializeRemoteBillingSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(ig.InitializeRemoteBillingFailed,t,{methodId:e}))})})}initializeShipping(e,t,i){return oe.create(n=>{n.next(l(ig.InitializeRemoteShippingRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializeShipping(e,t,i).then(({body:t={}})=>{n.next(l(ig.InitializeRemoteShippingSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(ig.InitializeRemoteShippingFailed,t,{methodId:e}))})})}initializePayment(e,t,i){return oe.create(n=>{n.next(l(ig.InitializeRemotePaymentRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.initializePayment(e,t,i).then(({body:t={}})=>{n.next(l(ig.InitializeRemotePaymentSucceeded,t,{methodId:e})),n.complete()}).catch(t=>{n.error(h(ig.InitializeRemotePaymentFailed,t,{methodId:e}))})})}loadSettings(e,t){return oe.create(i=>{i.next(l(ig.LoadRemoteSettingsRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.loadSettings(e,t).then(({body:t})=>{i.next(l(ig.LoadRemoteSettingsSucceeded,t,{methodId:e})),i.complete()}).catch(t=>{i.error(h(ig.LoadRemoteSettingsFailed,t,{methodId:e}))})})}signOut(e,t){return oe.create(i=>{i.next(l(ig.SignOutRemoteCustomerRequested,void 0,{methodId:e})),this._remoteCheckoutRequestSender.signOut(e,t).then(()=>{i.next(l(ig.SignOutRemoteCustomerSucceeded,void 0,{methodId:e})),i.complete()}).catch(t=>{i.error(h(ig.SignOutRemoteCustomerFailed,t,{methodId:e}))})})}forgetCheckout(e,t){return se(me(l(ig.ForgetCheckoutRemoteCustomerRequested,void 0,{methodId:e})),de(()=>{return i=this,n=void 0,o=function*(){return yield this._remoteCheckoutRequestSender.forgetCheckout(t),yield this._checkoutActionCreator.loadCurrentCheckout(),l(ig.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).pipe(ge(t=>Je(ig.ForgetCheckoutRemoteCustomerFailed,t,{methodId:e})))}updateCheckout(e,t){return l(ig.UpdateRemoteCheckout,t,{methodId:e})}}class ug{constructor(e){this._requestSender=e}initializeBilling(e,t,{timeout:i}={}){const n=`/remote-checkout/${e}/billing`;return this._requestSender.get(n,{params:t,timeout:i,headers:rt})}initializeShipping(e,t,{timeout:i}={}){const n=`/remote-checkout/${e}/shipping`;return this._requestSender.get(n,{params:t,timeout:i,headers:rt})}initializePayment(e,t,{timeout:i}={}){const n=`/remote-checkout/${e}/payment`;return this._requestSender.get(n,{params:t,timeout:i,headers:rt})}loadSettings(e,{timeout:t}={}){const i=`/remote-checkout/${e}/settings`;return this._requestSender.get(i,{timeout:t,headers:rt})}signOut(e,{timeout:t}={}){const i=`/remote-checkout/${e}/signout`;return this._requestSender.get(i,{timeout:t,headers:rt})}generateToken({timeout:e}={}){return this._requestSender.get("/remote-checkout-token",{timeout:e,headers:rt})}trackAuthorizationEvent({timeout:e}={}){return this._requestSender.post("/remote-checkout/events/shopper-checkout-service-provider-authorization-requested",{timeout:e,headers:rt})}forgetCheckout({timeout:e}={}){return this._requestSender.post("/remote-checkout/forget-checkout",{timeout:e,headers:rt})}}!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"}(cg||(cg={}));class hg{constructor(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}unassignItemsByAddress(e,t){return i=>{const n=i.getState();if(!n.checkout.getCheckout())throw new Xe(We.MissingCheckout);const r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=n.consignments.getConsignmentByAddress(r);if(!o)throw new Lt("No consignment found for the specified address");const a=this._removeLineItems(e.lineItems,o,n.cart.getCart());return a.length?this.updateConsignment({id:o.id,address:r,lineItems:a},t)(i):this.deleteConsignment(o.id,t)(i)}}assignItemsByAddress(e,t){return i=>{const n=i.getState(),r=this._consignmentHasAddress(e)?e.address:e.shippingAddress,o=n.consignments.getConsignmentByAddress(r);return this._createOrUpdateConsignment({id:o&&o.id,address:r,lineItems:this._addLineItems(e.lineItems,o,n.cart.getCart())},t)(i)}}selectShippingOption(e,t){return i=>oe.create(n=>{const r=i.getState(),o=r.checkout.getCheckout(),a=r.consignments.getConsignments();if(!o)throw new Xe(We.MissingCheckout);if(!a||!a.length)throw new Xe(We.MissingConsignments);const s={id:a[0].id,shippingOptionId:e},d={id:a[0].id};n.next(l(cg.UpdateShippingOptionRequested,void 0,d)),this._consignmentRequestSender.updateConsignment(o.id,s,t).then(({body:e})=>{n.next(l(cg.UpdateShippingOptionSucceeded,e,d)),n.complete()}).catch(e=>{n.error(h(cg.UpdateShippingOptionFailed,e,d))})})}loadShippingOptions(e){return t=>oe.create(i=>{const n=t.getState().checkout.getCheckout();if(!n)throw new Xe(We.MissingCheckout);i.next(l(cg.LoadShippingOptionsRequested)),this._checkoutRequestSender.loadCheckout(n.id,Object.assign(Object.assign({},e),{params:{include:[At.AvailableShippingOptions]}})).then(({body:e})=>{i.next(l(cg.LoadShippingOptionsSucceeded,e)),i.complete()}).catch(e=>{i.error(h(cg.LoadShippingOptionsFailed,e))})})}updateAddress(e,t){return i=>{const n=this._getUpdateAddressRequestBody(e,i),r=i.getState().consignments.getConsignments();return r&&r.length&&(n.id=r[0].id),this._createOrUpdateConsignment(n,t)(i)}}createConsignments(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r||!r.id)throw new Xe(We.MissingCheckout);n.next(l(cg.CreateConsignmentsRequested)),this._consignmentRequestSender.createConsignments(r.id,e,t).then(({body:e})=>{n.next(l(cg.CreateConsignmentsSucceeded,e)),n.complete()}).catch(e=>{n.error(h(cg.CreateConsignmentsFailed,e))})})}updateConsignment(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout();if(!r||!r.id)throw new Xe(We.MissingCheckout);const o={id:e.id};n.next(l(cg.UpdateConsignmentRequested,void 0,o)),this._consignmentRequestSender.updateConsignment(r.id,e,t).then(({body:e})=>{n.next(l(cg.UpdateConsignmentSucceeded,e,o)),n.complete()}).catch(e=>{n.error(h(cg.UpdateConsignmentFailed,e,o))})})}deleteConsignment(e,t){return i=>oe.create(n=>{const r=i.getState().checkout.getCheckout(),o={id:e};if(!r||!r.id)throw new Xe(We.MissingCheckout);n.next(l(cg.DeleteConsignmentRequested,void 0,o)),this._consignmentRequestSender.deleteConsignment(r.id,e,t).then(({body:e})=>{n.next(l(cg.DeleteConsignmentSucceeded,e,o)),n.complete()}).catch(e=>{n.error(h(cg.DeleteConsignmentFailed,e,o))})})}updateShippingOption(e,t){return i=>oe.create(n=>{var r;const o=i.getState().checkout.getCheckout(),a=i.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 n.complete();if(!o||!o.id)throw new Xe(We.MissingCheckout);const s={id:e.id};n.next(l(cg.UpdateShippingOptionRequested,void 0,s)),this._consignmentRequestSender.updateConsignment(o.id,e,t).then(({body:e})=>{n.next(l(cg.UpdateShippingOptionSucceeded,e,s)),n.complete()}).catch(e=>{n.error(h(cg.UpdateShippingOptionFailed,e,s))})})}_createOrUpdateConsignment(e,t){return i=>{const n=i.getState().checkout.getCheckout();if(!n||!n.id)throw new Xe(We.MissingCheckout);return this._isUpdateConsignmentRequest(e)?this.updateConsignment(e,t)(i):this.createConsignments([e],t)(i)}}_getUpdateAddressRequestBody(e,t){const i=t.getState().cart.getCart();if(!i)throw new Xe(We.MissingCart);const{physicalItems:n,customItems:r=[]}=i.lineItems;return{address:e,lineItems:[...n,...r].map(e=>({itemId:e.id,quantity:e.quantity}))}}_removeLineItems(e,t,i){if(!i)throw new Xe(We.MissingCart);return this._hydrateLineItems(t.lineItemIds,i).map(t=>{const i=S(e,e=>e.itemId===t.itemId);return Object.assign(Object.assign({},t),{quantity:i?t.quantity-i.quantity:t.quantity})}).filter(e=>e.quantity>0)}_addLineItems(e,t,i){if(!t)return e;if(!i)throw new Xe(We.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,i)).filter(e=>e.quantity>0)}_hydrateLineItems(e,t){return e.map(e=>{const i=S(t.lineItems.physicalItems,t=>t.id===e);return{itemId:e,quantity:i?i.quantity:0}})}_isUpdateConsignmentRequest(e){return!!e.id}_consignmentHasAddress(e){return"object"==typeof e&&"address"in e}}const pg=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.physicalItems.stockPosition","cart.lineItems.digitalItems.options","cart.lineItems.digitalItems.stockPosition","customer","promotions.banners"];class mg{constructor(e){this._requestSender=e}createConsignments(e,t,{timeout:i,params:{include:n}={}}={}){const r=`/api/storefront/checkouts/${e}/consignments`,o=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(r,{body:t,params:{include:Xt(pg,n)},headers:o,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}updateConsignment(e,t,{timeout:i,params:{include:n}={}}={}){const{id:r}=t,o=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(t,["id"]),a=`/api/storefront/checkouts/${e}/consignments/${r}`,s=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.put(a,{body:o,params:{include:Xt(pg,n)},headers:s,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}deleteConsignment(e,t,{timeout:i}={}){const n=`/api/storefront/checkouts/${e}/consignments/${t}`,r=Object.assign({Accept:nt.JsonV1},rt),o=Mt(pg);return this._requestSender.delete(n,{params:{include:o},headers:r,timeout:i}).catch(e=>{if("empty_cart"===e.body.type)throw new it;throw e})}}var yg,gg;!function(e){e.LoadShippingCountriesRequested="LOAD_SHIPPING_COUNTRIES_REQUESTED",e.LoadShippingCountriesSucceeded="LOAD_SHIPPING_COUNTRIES_SUCCEEDED",e.LoadShippingCountriesFailed="LOAD_SHIPPING_COUNTRIES_FAILED"}(yg||(yg={}));class vg{constructor(e,t){this._shippingCountryRequestSender=e,this._store=t}loadCountries(e){const{checkout:t}=this._store.getState(),i=t.getCheckout(),n=i?i.channelId:null;return oe.create(t=>{t.next(l(yg.LoadShippingCountriesRequested)),this._shippingCountryRequestSender.loadCountries(n,e).then(e=>{t.next(l(yg.LoadShippingCountriesSucceeded,e.body.data)),t.complete()}).catch(e=>{t.error(h(yg.LoadShippingCountriesFailed,e))})})}}class fg{constructor(e,t){this._requestSender=e,this._config=t}loadCountries(e,{timeout:t}={}){const i="/internalapi/v1/shipping/countries"+(e?`?channel_id=${e}`:""),n=Object.assign({"Accept-Language":this._config.locale},rt);return this._requestSender.get(i,{headers:n,timeout:t})}}!function(e){e.ApplyStoreCreditRequested="APPLY_STORE_CREDIT_REQUESTED",e.ApplyStoreCreditSucceeded="APPLY_STORE_CREDIT_SUCCEEDED",e.ApplyStoreCreditFailed="APPLY_STORE_CREDIT_FAILED"}(gg||(gg={}));var Sg;class wg{constructor(e){this._storeCreditRequestSender=e}applyStoreCredit(e,t){return i=>se(me(l(gg.ApplyStoreCreditRequested)),de(()=>{return n=this,r=void 0,a=function*(){const n=i.getState().checkout.getCheckout();if(!n)throw new Xe(We.MissingCheckout);const{body:r}=yield e?this._storeCreditRequestSender.applyStoreCredit(n.id,t):this._storeCreditRequestSender.removeStoreCredit(n.id,t);return l(gg.ApplyStoreCreditSucceeded,r)},new((o=void 0)||(o=Promise))(function(e,t){function i(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 n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,s)}d((a=a.apply(n,r||[])).next())});var n,r,o,a})).pipe(ge(e=>Je(gg.ApplyStoreCreditFailed,e)))}}class Ig{constructor(e){this._requestSender=e}applyStoreCredit(e,{timeout:t}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,n=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post(i,{headers:n,timeout:t,params:{include:Mt(Et)}})}removeStoreCredit(e,{timeout:t}={}){const i=`/api/storefront/checkouts/${e}/store-credit`,n=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.delete(i,{headers:n,timeout:t,params:{include:Mt(Et)}})}}!function(e){e.UpdateSubscriptionsRequested="UPDATE_SUBSCRIPTIONS_REQUESTED",e.UpdateSubscriptionsSucceeded="UPDATE_SUBSCRIPTIONS_SUCCEEDED",e.UpdateSubscriptionsFailed="UPDATE_SUBSCRIPTIONS_FAILED"}(Sg||(Sg={}));class _g extends It{constructor(e){super(e),this.name="UpdateSubscriptionsError",this.type="update_subscriptions"}}class Cg{constructor(e){this._subscriptionsRequestSender=e}updateSubscriptions(e,t){return se(me(l(Sg.UpdateSubscriptionsRequested)),de(()=>{return i=this,n=void 0,o=function*(){const{body:i}=yield this._subscriptionsRequestSender.updateSubscriptions(e,t);return l(Sg.UpdateSubscriptionsSucceeded,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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).pipe(ge(e=>Je(Sg.UpdateSubscriptionsFailed,new _g(e))))}}class bg{constructor(e){this._requestSender=e}updateSubscriptions(e,{timeout:t}={}){const i=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:i,timeout:t})}}function Pg(e){return M(e)}const Og=U(e=>Array.isArray(e)?e.map(e=>Eg(e)):Pg(e)?Object.keys(e).reduce((t,i)=>Object.assign(Object.assign({},t),{[i]:Eg(e[i])}),{}):e);Og.cache=new WeakMap;const Eg=e=>"object"==typeof e&&null!==e?Og(e):e;function Ag(e){return(...t)=>Eg(e(...t))}function Tg({billingAddress:{getBillingAddress:e,getBillingAddressOrThrow:t},cart:{getCart:i,getCartOrThrow:n,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:v,getCustomerOrThrow:f},instruments:{getCardInstrument:S,getCardInstrumentOrThrow:w,getInstruments:I,getInstrumentsMeta:_},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:N},paymentMethods:{getPaymentMethod:x,getPaymentMethodOrThrow:F,getPaymentMethodsMeta:R},paymentProviderCustomer:{getPaymentProviderCustomer:L,getPaymentProviderCustomerOrThrow:B},paymentStrategies:{isInitialized:j},shippingAddress:{getShippingAddress:U,getShippingAddressOrThrow:q,getShippingAddresses:V,getShippingAddressesOrThrow:G},shippingCountries:{getShippingCountries:H}}){return{getHost:Ag(c),getLocale:Ag(l),getCartLocale:Ag(r),getBillingAddress:Ag(e),getBillingAddressOrThrow:Ag(t),getCart:Ag(i),getCartOrThrow:Ag(n),getCheckout:Ag(o),getCheckoutOrThrow:Ag(a),getCountries:Ag(g),getStoreConfig:Ag(u),getStoreConfigOrThrow:Ag(h),getConfig:Ag(p),getConsignments:Ag(m),getConsignmentsOrThrow:Ag(y),getContextConfig:Ag(d),getCustomer:Ag(v),getCustomerOrThrow:Ag(f),getCardInstrument:Ag(S),getInstruments:Ag(I),getCardInstrumentOrThrow:Ag(w),getOrder:Ag(C),getOrderOrThrow:Ag(b),getOrderMeta:Ag(P),getInstrumentsMeta:Ag(_),getPaymentToken:O,getPaymentTokenOrThrow:E,getPaymentId:A,getPaymentIdOrThrow:T,getPaymentStatus:k,getPaymentStatusOrThrow:D,getPaymentRedirectUrl:M,getPaymentRedirectUrlOrThrow:z,getPaymentMethod:Ag(x),getPaymentMethodOrThrow:Ag(F),getPaymentMethodsMeta:Ag(R),getPaymentProviderCustomer:Ag(L),getPaymentProviderCustomerOrThrow:Ag(B),getShippingAddress:Ag(U),getShippingAddressOrThrow:Ag(q),getShippingAddresses:Ag(V),getShippingAddressesOrThrow:Ag(G),getShippingCountries:Ag(H),getOutstandingBalance:Ag(s),isPaymentDataRequired:N,isPaymentMethodInitialized:j}}var kg,Dg=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Mg{constructor(e,t,i,n,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S){this._store=e,this._storeProjectionFactory=t,this._checkoutActionCreator=i,this._checkoutValidator=n,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=v,this._remoteCheckoutActionCreator=f,this._paymentStrategyWidgetActionCreator=S,this._storeProjection=this._storeProjectionFactory.create(this._store)}createHostedForm(e,t){const i=this._storeProjection.getState().getCheckoutOrThrow().id;return this._hostedFormFactory.create(e,t,i)}subscribe(e,...t){return this._storeProjection.subscribe(e,...t)}getState(){return this._storeProjection.getState()}initializeOffsitePayment(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.initializeOffsitePayment(e)),this._storeProjection.getState()})}loadCheckout(e){return Dg(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 Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()),this._storeProjection.getState()})}loadPaymentMethod(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e,t)),this._storeProjection.getState()})}loadPaymentMethods(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods(e)),this._storeProjection.getState()})}submitOrder(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.submitOrder(e,t)),this._storeProjection.getState()})}submitPayment(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentActionCreator.submitPayment(e)),this._storeProjection.getState()})}finalizeOrder(e){return Dg(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 Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(e)),this._storeProjection.getState()})}updateShippingAddress(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.updateAddress(e)),this._storeProjection.getState()})}selectShippingOption(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t)),this._storeProjection.getState()})}signInCustomer(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signInCustomer(e,t)),this._storeProjection.getState()})}signOutCustomer(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._customerActionCreator.signOutCustomer(e)),this._storeProjection.getState()})}createBuyNowCart(e,t){return Dg(this,void 0,void 0,function*(){const{body:i}=yield this._cartRequestSender.createBuyNowCart(e,t);return i})}applyStoreCredit(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(e,t)),this._storeProjection.getState()})}applyCoupon(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.applyCoupon(e,t)),this._storeProjection.getState()})}removeCoupon(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._couponActionCreator.removeCoupon(e,t)),this._storeProjection.getState()})}verifyCheckoutSpamProtection(){return Dg(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 Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._orderActionCreator.loadCurrentOrder(e)),this._storeProjection.getState()})}updatePaymentProviderCustomer(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(e)),this._storeProjection.getState()})}loadShippingCountries(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._shippingCountryActionCreator.loadCountries(e)),this._storeProjection.getState()})}deleteConsignment(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._consignmentActionCreator.deleteConsignment(e,t)),this._storeProjection.getState()})}initializePayment(e,t,i){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(e,t,i)),this._storeProjection.getState()})}forgetCheckout(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.forgetCheckout(e,t)),this._storeProjection.getState()})}remoteCheckoutSignOut(e,t){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e,t)),this._storeProjection.getState()})}validateCheckout(e,t){return Dg(this,void 0,void 0,function*(){yield this._checkoutValidator.validate(e,t)})}handlePaymentHumanVerification(e,t){return Dg(this,void 0,void 0,function*(){return"string"==typeof e?this._paymentHumanVerificationHandler.handle(e,null!=t?t:""):this._paymentHumanVerificationHandler.handle(e)})}widgetInteraction(e){return Dg(this,void 0,void 0,function*(){return yield this._store.dispatch(this._paymentStrategyWidgetActionCreator.widgetInteraction(e),{queueId:"widgetInteraction"}),this._storeProjection.getState()})}}class zg{constructor(e){this._transformSelectors=e}create(e){return ct(e,this._transformSelectors)}}function Ng(e){const{config:{getHost:t,getLocale:n}}=e.getState(),r=i({host:t()}),a=new zg(Tg),s=new ti(new Qt(r),new St(new bt(r)),new ni(new ri(r))),d=new Vm(new Qt(r)),c=new cy(e),l=new km(new Em(r),new Vm(new Qt(r))),u=new tt(new at(r),new Cg(new bg(r))),h=new hg(new mg(r),new Qt(r)),p=new zm(new Nm(r)),m=new ly(new uy(Dm(e)),l,new Dy,new Jm(vi(o()))),y=new Jm(vi(o())),g=new Ht(new $t(r),s,new ui(vi(o()),new fi(r))),v=new wg(new Ig(r)),f=new Ot(new zt(r)),S=vi(o()),w=new fi(r),I=new ui(S,w),_=new sg(r),C=new dg,b=new vg(new fg(r,{locale:n()}),e),P=new lg(new ug(r),s),O=new Bm;return new Mg(e,a,s,d,c,l,u,h,p,m,y,g,_,v,f,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"}(kg||(kg={}));class xg{constructor(e){this._instrumentRequestSender=e}loadInstruments(){return e=>oe.create(t=>{t.next(l(kg.LoadInstrumentsRequested));const i=this._getSessionContext(e),n=this._getCurrentAccessToken(e),r=this._getShippingAddress(e);return this._getValidAccessToken(n).then(e=>this._instrumentRequestSender.loadInstruments(Object.assign(Object.assign({},i),{authToken:e.vaultAccessToken}),r).then(({body:i})=>{t.next(l(kg.LoadInstrumentsSucceeded,i,e)),t.complete()})).catch(e=>{t.error(h(kg.LoadInstrumentsFailed,e))})})}deleteInstrument(e){return t=>oe.create(i=>{i.next(l(kg.DeleteInstrumentRequested,void 0,{instrumentId:e}));const n=this._getSessionContext(t),r=this._getCurrentAccessToken(t);return this._getValidAccessToken(r).then(t=>this._instrumentRequestSender.deleteInstrument(Object.assign(Object.assign({},n),{authToken:t.vaultAccessToken}),e).then(({body:n})=>{i.next(l(kg.DeleteInstrumentSucceeded,n,Object.assign({instrumentId:e},t))),i.complete()})).catch(t=>{i.error(h(kg.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(),i=t.getInstrumentsMeta();if(i)return{vaultAccessToken:i.vaultAccessToken,vaultAccessExpiry:i.vaultAccessExpiry}}_getValidAccessToken(e){return e&&this._isValidVaultAccessToken(e)?Promise.resolve(e):this._instrumentRequestSender.getVaultAccessToken().then(({body:e})=>e)}_getShippingAddress(e){const t=e.getState(),i=t.shippingAddress.getShippingAddresses();return i.length>1?i:t.shippingAddress.getShippingAddress()}_getSessionContext(e){const t=e.getState(),i=t.config.getStoreConfig(),n=t.cart.getCart();if(!i)throw new Xe(We.MissingCheckoutConfig);if(!n)throw new Xe(We.MissingCart);const{customerId:r}=n,{storeId:o}=i.storeProfile,{code:a}=i.shopperCurrency.isTransactional?i.shopperCurrency:i.currency;return{customerId:r,storeId:o,currencyCode:a}}}var Fg,Rg,Lg=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i};class Bg{transformResponse(e){const t=this._transformResponse(e),{body:i}=t,n=Lg(t,["body"]);return Object.assign(Object.assign({},n),{body:{vaultedInstruments:this._transformVaultedInstruments(i.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,i=Lg(e,["data"]);return Object.assign(Object.assign({},i),{body:t})}}class jg{constructor(e,t){this._client=e,this._requestSender=t,this._transformer=new Bg}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 i=Object.assign(Object.assign({},e),{instrumentId:t});return new Promise((e,t)=>{this._client.deleteShopperInstrument(i,(i,n)=>i?t(this._transformer.transformErrorResponse(i)):e(this._transformer.transformResponse(n)))})}_loadInstruments(e){return new Promise((t,i)=>{this._client.loadInstruments(e,(e,n)=>e?i(this._transformer.transformErrorResponse(e)):t(this._transformer.transformResponse(n)))})}_loadInstrumentsWithAddress(e,t){const i=Object.assign(Object.assign({},e),{shippingAddress:Array.isArray(t)?t.map(e=>hy(e)):hy(t)});return new Promise((e,t)=>{this._client.loadInstrumentsWithAddress(i,(i,n)=>i?t(this._transformer.transformErrorResponse(i)):e(this._transformer.transformResponse(n)))})}}!function(e){e.LoadPickupOptionsRequested="LOAD_PICKUP_OPTIONS_REQUESTED",e.LoadPickupOptionsSucceeded="LOAD_PICKUP_OPTIONS_SUCCEEDED",e.LoadPickupOptionsFailed="LOAD_PICKUP_OPTIONS_FAILED"}(Fg||(Fg={}));class Ug{constructor(e){this._pickupOptionRequestSender=e}loadPickupOptions(e){return t=>new oe(i=>{const n=this._hydrateApiQuery(t,e);i.next(l(Fg.LoadPickupOptionsRequested)),this._pickupOptionRequestSender.fetchPickupOptions(n).then(t=>{i.next(l(Fg.LoadPickupOptionsSucceeded,t.body.results,e)),i.complete()}).catch(e=>{i.error(h(Fg.LoadPickupOptionsFailed,e))})})}_hydrateApiQuery(e,t){const i=e.getState(),n=i.cart.getCartOrThrow();if(!n)throw new Xe(We.MissingCart);const r=i.consignments.getConsignmentById(t.consignmentId);if(!r)throw new Xe(We.MissingConsignments);const o=r.lineItemIds,a=n.lineItems.physicalItems.filter(e=>P(o,e.id)).map(e=>({variantId:e.variantId,quantity:e.quantity}));return{searchArea:t.searchArea,items:a}}}class qg{constructor(e){this._requestSender=e}fetchPickupOptions(e){return this._requestSender.post("/api/storefront/pickup-options",{headers:Object.assign({Accept:nt.Json},rt),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"}(Rg||(Rg={}));class Vg{constructor(e){this._strategyRegistry=e}updateAddress(e,t){return i=>oe.create(n=>{const r=i.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;n.next(l(Rg.UpdateAddressRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).updateAddress(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{n.next(l(Rg.UpdateAddressSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Rg.UpdateAddressFailed,e,{methodId:o}))})})}selectOption(e,t){return i=>oe.create(n=>{const r=i.getState().payment.getPaymentId(),o=t&&t.methodId||r&&r.providerId;n.next(l(Rg.SelectOptionRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).selectOption(e,Object.assign(Object.assign({},t),{methodId:o})).then(()=>{n.next(l(Rg.SelectOptionSucceeded,void 0,{methodId:o})),n.complete()}).catch(e=>{n.error(h(Rg.SelectOptionFailed,e,{methodId:o}))})})}initialize(e){return t=>oe.create(i=>{const n=t.getState(),r=n.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId,a=Object.assign(Object.assign({},e),{methodId:o});if(o&&n.shippingStrategies.isInitialized(o))return i.complete();i.next(l(Rg.InitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).initialize(a).then(()=>{i.next(l(Rg.InitializeSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Rg.InitializeFailed,e,{methodId:o}))})})}deinitialize(e){return t=>oe.create(i=>{const n=t.getState(),r=n.payment.getPaymentId(),o=e&&e.methodId||r&&r.providerId;if(o&&!n.shippingStrategies.isInitialized(o))return i.complete();i.next(l(Rg.DeinitializeRequested,void 0,{methodId:o})),this._strategyRegistry.get(o).deinitialize(Object.assign(Object.assign({},e),{methodId:o})).then(()=>{i.next(l(Rg.DeinitializeSucceeded,void 0,{methodId:o})),i.complete()}).catch(e=>{i.error(h(Rg.DeinitializeFailed,e,{methodId:o}))})})}widgetInteraction(e,t){return oe.create(i=>{const n={methodId:t&&t.methodId};i.next(l(Rg.WidgetInteractionStarted,void 0,n)),e().then(()=>{i.next(l(Rg.WidgetInteractionFinished,void 0,n)),i.complete()}).catch(e=>{i.error(h(Rg.WidgetInteractionFailed,e,n))})})}}var Gg,Hg=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class $g{constructor(e,t,i,n,r){this._store=e,this._consignmentActionCreator=t,this._paymentMethodActionCreator=i,this._amazonPayV2PaymentProcessor=n,this._shippingStrategyActionCreator=r}updateAddress(e,t){const i=this._store.getState().shippingAddress.getShippingAddress();if(!i)throw new Xe(We.MissingShippingAddress);const n=Object.assign(Object.assign({},i),{customFields:e.customFields});return this._store.dispatch(this._consignmentActionCreator.updateAddress(n,t))}selectOption(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))}initialize(e){return Hg(this,void 0,void 0,function*(){const{amazonpay:t,methodId:i}=e;if(!t||!i)throw new Lt('Unable to proceed because "options.amazonpay" argument is not provided.');const n=(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i))).paymentMethods.getPaymentMethodOrThrow(i);yield this._amazonPayV2PaymentProcessor.initialize(n);const{paymentToken:r,region:o}=n.initializationData,a=t.editAddressButtonId;if(r&&a){const e=this._shouldShowLoadingSpinner(o);this._bindEditButton(a,r,"changeAddress",e)}return this._store.getState()})}deinitialize(){return Hg(this,void 0,void 0,function*(){return yield this._amazonPayV2PaymentProcessor.deinitialize(),Promise.resolve(this._store.getState())})}_bindEditButton(e,t,i,n){const r=document.getElementById(e);if(r&&r.parentNode){if(n){const e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener("click",()=>this._showLoadingSpinner())}this._amazonPayV2PaymentProcessor.bindButton(e,t,i)}}_showLoadingSpinner(){return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction(()=>new Promise(pe)),{queueId:"widgetInteraction"})}_shouldShowLoadingSpinner(e){return"us"!==e}}!function(e){e.CVV="cvv",e.PAN="pan"}(Gg||(Gg={}));var Wg=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Yg{constructor(e,t,i,n,r,o){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=i,this._paymentMethodActionCreator=n,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 Wg(this,void 0,void 0,function*(){const{methodId:i,braintreefastlane:n,fastlane:r}=e||{},o=r||n,{onPayPalFastlaneAddressChange:a}=o||{};if(!i)throw new Lt('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(i),{clientToken:n,isFastlaneStylingEnabled:r}=(null==e?void 0:e.initializationData)||{};n||(yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i)));const a=Po(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(i,a)}"function"==typeof a&&(yield this._shouldUseBraintreeFastlaneShippingComponent(i))&&a(()=>this._handleBraintreeFastlaneShippingAddressChange())}catch(e){}return Promise.resolve(this._store.getState())})}_shouldRunAuthenticationFlow(){var e;const t=this._store.getState(),i=null===(e=t.cart.getCart())||void 0===e?void 0:e.id,n=Nr.get("bc-fastlane-sessionId")||"",r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=vl(r)?r:{};return(null==o?void 0:o.authenticationState)!==Tn.CANCELED&&!(null==o?void 0:o.authenticationState)&&n===i}_runAuthenticationFlowOrThrow(e,t){var i,n;return Wg(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 Xe(We.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===(i=r.customer.getCustomer())||void 0===i?void 0:i.email)||(null===(n=r.billingAddress.getBillingAddress())||void 0===n?void 0:n.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===Tn.CANCELED)return yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:[],instruments:[]})),void Nr.remove("bc-fastlane-sessionId");const v=this._getPayPalBillingAddress(g),f=g.shippingAddress,S=g.shippingAddress.phoneNumber,w=this._mapPayPalToBcAddress(f,a,S),I=this._mapPayPalToBcAddress(v,a,S);if(I&&w){const t=this._mergeShippingAndBillingAddresses(w,I),i=this._mapPayPalToBcInstrument(e,g.card),n=i?[i]:[];yield this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({authenticationState:y,addresses:t,instruments:n})),I&&(yield this._store.dispatch(this._billingAddressActionCreator.updateAddress(Object.assign(Object.assign({},I),{id:String(I.id)})))),w&&o.lineItems.physicalItems.length>0&&(yield this._store.dispatch(this._consignmentActionCreator.updateAddress(w)))}})}_getPayPalBillingAddress(e){const{name:t,card:i}=e,n=i.paymentSource.card.billingAddress;return Object.assign(Object.assign({},n),{firstName:n.firstName||(null==t?void 0:t.firstName),lastName:n.lastName||(null==t?void 0:t.lastName)})}_getCountryNameByCountryCode(e,t){const i=t.find(t=>t.code===e);return(null==i?void 0:i.name)||""}_mapPayPalToBcAddress(e,t,i,n){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:i||"",customFields:n||[]}}_normalizeAddress(e){return G(e,["id"])}_mergeShippingAndBillingAddresses(e,t){return A(this._normalizeAddress(e),this._normalizeAddress(t))?[e]:[e,t]}_mapPayPalToBcInstrument(e,t){if(!t)return;const{id:i,paymentSource:n}=t,{brand:r,expiry:o,lastDigits:a}=n.card,[s,d]=o.split("-");return{bigpayToken:i,brand:r,defaultInstrument:!1,expiryMonth:d,expiryYear:s,iin:"",last4:a,method:e,provider:e,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:Gg.CVV,type:"card"}}_handleBraintreeFastlaneShippingAddressChange(){var e;return Wg(this,void 0,void 0,function*(){const t=this._store.getState().countries.getCountries()||[],i=yield this._braintreeIntegrationService.getBraintreeFastlane(),{selectionChanged:n,selectedAddress:r}=yield i.profile.showShippingAddressSelector();if(n){const i=this._store.getState(),n=i.shippingAddress.getShippingAddressesOrThrow(),o=i.paymentProviderCustomer.getPaymentProviderCustomer(),a=vl(o)?o:{},s=this._mapPayPalToBcAddress(r,t,r.phoneNumber,null===(e=n[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 A(this._normalizeAddress(e),this._normalizeAddress(t))}_shouldUseBraintreeFastlaneShippingComponent(e){var t;return Wg(this,void 0,void 0,function*(){const i=this._store.getState().paymentProviderCustomer.getPaymentProviderCustomer(),n=vl(i)?i:{};if(n&&n!==Tn.CANCELED){const i=yield this._getBraintreePaymentMethodOrThrow(e);return!!(null===(t=null==i?void 0:i.initializationData)||void 0===t?void 0:t.isFastlaneEnabled)}return!1})}_getBraintreePaymentMethodOrThrow(e){return Wg(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 Kg{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 Jg=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Zg{constructor(e,t,i,n,r,o,a){this._store=e,this._billingAddressActionCreator=t,this._consignmentActionCreator=i,this._paymentMethodActionCreator=n,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 Jg(this,void 0,void 0,function*(){const{methodId:t,paypalcommercefastlane:i,fastlane:n}=e||{},r=n||i,{onPayPalFastlaneAddressChange:o,styles:a}=r||{};if(!t)throw new Lt('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 Jg(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!==Ms.CANCELED}_initializePayPalSdk(e,t){var i;return Jg(this,void 0,void 0,function*(){const n=this._store.getState().cart.getCartOrThrow(),r=yield this._getPayPalPaymentMethodOrThrow(e),{isDeveloperModeApplicable:o,isFastlaneStylingEnabled:a}=(null==r?void 0:r.initializationData)||{},s=!!o,d=qs(a?null===(i=null==r?void 0:r.initializationData)||void 0===i?void 0:i.fastlaneStyles:{},t),c=yield this._paypalSdkScriptLoader.getPayPalFastlaneSdk(r,n.currency.code,n.id);yield this._paypalCommerceFastlaneUtils.initializePayPalFastlane(c,s,d)})}_authenticateUserWithFastlaneOtp(e){var t,i;return Jg(this,void 0,void 0,function*(){const n=this._store.getState(),r=n.cart.getCartOrThrow(),o=null===(t=n.customer.getCustomer())||void 0===t?void 0:t.email,a=null===(i=n.billingAddress.getBillingAddress())||void 0===i?void 0:i.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===Ms.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 Jg(this,void 0,void 0,function*(){const t=this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow(),{selectionChanged:i,selectedAddress:n}=yield t.profile.showShippingAddressSelector();if(i){const t=this._store.getState(),i=t.shippingAddress.getShippingAddressesOrThrow(),r=t.paymentProviderCustomer.getPaymentProviderCustomer(),o=cp(r)?r:{},a=this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(n.address,n.name,n.phoneNumber,null===(e=i[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 Xg;class Qg{constructor(e,t,i,n){this._store=e,this._stripeScriptLoader=t,this._consignmentActionCreator=i,this._paymentMethodActionCreator=n}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,i=void 0,r=function*(){if(!e.stripeupe)throw new Lt('Unable to proceed because "options" argument is not provided.');const{container:t,gatewayId:i,methodId:n,onChangeShipping:r,getStyles:o,availableCountries:a,getStripeState:s}=e.stripeupe;Object.entries(e.stripeupe).forEach(([e,t])=>{if(!t)throw new Lt(`Unable to proceed because "${e}" argument is not provided.`)});const d=yield this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i,{params:{method:n}})),c=d.paymentMethods.getPaymentMethodOrThrow(n,i),{initializationData:l}=c;if(!c||!c.initializationData.stripePublishableKey||!c.clientToken)throw new Xe(We.MissingPaymentMethod);let u;this._stripeUPEClient=yield this._stripeScriptLoader.getStripeClient(l,d.cart.getLocale(),ba.V3,Da,Ma);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(),v=y.find(e=>"phone"===e.name);let f={mode:Sa.SHIPPING,allowedCountries:[a],fields:{phone:"always"},validation:{phone:{required:v&&v.required?"always":"never"}},display:{name:wa.SPLIT}};if(g){const{stateOrProvinceCode:e,countryCode:t,lastName:i,firstName:n,phone:r,address1:o,address2:a,city:d,postalCode:c}=g,l=e&&t?s(t,e):e;f=Object.assign(Object.assign({},f),{defaultValues:{firstName:n,lastName:i,phone:r,address:{line1:o,line2:a,city:d,state:l,postal_code:c,country:t}}})}let S=this._stripeElements.getElement(Pa.SHIPPING);return S&&S.destroy(),S=this._stripeElements.create(Pa.SHIPPING,f),S.on(Ea.CHANGE,e=>{if(!("isNewAddress"in e))throw new Xe(We.MissingShippingAddress);(e.complete||e.isNewAddress)&&(this.sendData&&clearTimeout(this.sendData),this.sendData=setTimeout(()=>{r(Object.assign(Object.assign({},e),{phoneFieldRequired:!!v&&v.required}))},1e3))}),S.mount(`#${t}`),Promise.resolve(this._store.getState())},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,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"}(Xg||(Xg={}));class ev{constructor(e){this._requestSender=e}sendSignInEmail(e,t){return se(me(l(Xg.SendSignInEmailRequested)),de(()=>{return i=this,n=void 0,o=function*(){const{body:i}=yield this._requestSender.sendSignInEmail(e,t);return l(Xg.SendSignInEmailSucceeded,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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o})).pipe(ge(e=>Je(Xg.SendSignInEmailFailed,e)))}}class tv{constructor(e){this._requestSender=e}sendSignInEmail({email:e,redirectUrl:t},{timeout:i}={}){const n=Object.assign({Accept:nt.JsonV1},rt);return this._requestSender.post("/login.php?action=passwordless_login",{body:{email:e,redirect_url:t||wi(window.top?window.top.location.href:"").pathname},headers:n,timeout:i})}}class iv{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 nv=class{constructor(e,t,i,n,r,o,a,s,d,c,l,u,h,p,m,y,g,v,f,S,w,I,_,C,b,P,O,E){this._store=e,this._storeProjection=t,this._extensionMessenger=i,this._extensionEventBroadcaster=n,this._billingAddressActionCreator=r,this._checkoutActionCreator=o,this._configActionCreator=a,this._customerActionCreator=s,this._consignmentActionCreator=d,this._countryActionCreator=c,this._couponActionCreator=l,this._customerStrategyActionCreator=u,this._errorActionCreator=h,this._giftCertificateActionCreator=p,this._instrumentActionCreator=m,this._orderActionCreator=y,this._paymentMethodActionCreator=g,this._paymentStrategyActionCreator=v,this._pickupOptionActionCreator=f,this._shippingCountryActionCreator=S,this._shippingStrategyActionCreator=w,this._signInEmailActionCreator=I,this._spamProtectionActionCreator=_,this._storeCreditActionCreator=C,this._subscriptionsActionCreator=b,this._formFieldsActionCreator=P,this._extensionActionCreator=O,this._workerExtensionMessenger=E,this._errorTransformer=function(e="development"===ht()){return new iv(t=>{if(!e||!function(e){return!(!e.subtype&&!e.type)}(t))return t.message;switch(t.subtype||t.type){case We.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 We.MissingCart:case We.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 We.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 We.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 We.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 We.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 si.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 si.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 si.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 i=this._checkoutActionCreator.updateCheckout(e,t);return this._dispatch(i)}loadOrder(e,t){const i=this._orderActionCreator.loadOrder(e,t),n=this._formFieldsActionCreator.loadFormFields(t),r=this._configActionCreator.loadConfig(t);return Promise.all([this._dispatch(i),this._dispatch(r,{queueId:"config"}),this._dispatch(n,{queueId:"formFields"})]).then(()=>this.getState())}submitOrder(e,t){const i=this._paymentStrategyActionCreator.execute(e,t);return this._dispatch(i,{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 i=this._paymentMethodActionCreator.loadPaymentMethodsById(e,t);return this._dispatch(i,{queueId:"paymentMethods"})}loadPaymentMethod(e,t){const i=this._paymentMethodActionCreator.loadPaymentMethod(e,t);return this._dispatch(i,{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 i=this._signInEmailActionCreator.sendSignInEmail(e,t);return this._dispatch(i,{queueId:"signInEmail"})}createCustomerAccount(e,t){const i=this._customerActionCreator.createCustomer(e,t);return this._dispatch(i)}createCustomerAddress(e,t){const i=this._customerActionCreator.createAddress(e,t);return this._dispatch(i)}updateSubscriptions(e,t){const i=this._subscriptionsActionCreator.updateSubscriptions(e,t);return this._dispatch(i,{queueId:"subscriptions"})}continueAsGuest(e,t){const i=this._billingAddressActionCreator.continueAsGuest(e,t);return this._dispatch(i)}signInCustomer(e,t){const i=this._customerStrategyActionCreator.signIn(e,t);return this._dispatch(i,{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 i=this._shippingStrategyActionCreator.selectOption(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}updateShippingAddress(e,t){const i=this._shippingStrategyActionCreator.updateAddress(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}createConsignments(e,t){const i=this._consignmentActionCreator.createConsignments(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}deleteConsignment(e,t){const i=this._consignmentActionCreator.deleteConsignment(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}updateConsignment(e,t){const i=this._consignmentActionCreator.updateConsignment(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}assignItemsToAddress(e,t){const i=this._consignmentActionCreator.assignItemsByAddress(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}unassignItemsToAddress(e,t){const i=this._consignmentActionCreator.unassignItemsByAddress(e,t);return this._dispatch(i,{queueId:"shippingStrategy"})}selectConsignmentShippingOption(e,t,i){const n=this._consignmentActionCreator.updateShippingOption({id:e,shippingOptionId:t},i);return this._dispatch(n,{queueId:"shippingStrategy"})}updateBillingAddress(e,t={}){const i=this._billingAddressActionCreator.updateAddress(e,t);return this._dispatch(i)}applyStoreCredit(e,t){const i=this._storeCreditActionCreator.applyStoreCredit(e,t);return this._dispatch(i)}applyCoupon(e,t){const i=this._couponActionCreator.applyCoupon(e,t);return this._dispatch(i)}removeCoupon(e,t){const i=this._couponActionCreator.removeCoupon(e,t);return this._dispatch(i)}applyGiftCertificate(e,t){const i=this._giftCertificateActionCreator.applyGiftCertificate(e,t);return this._dispatch(i)}removeGiftCertificate(e,t){const i=this._giftCertificateActionCreator.removeGiftCertificate(e,t);return this._dispatch(i)}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 i=this,n=void 0,o=function*(){const i=this._extensionActionCreator.renderExtension(e,t,this._workerExtensionMessenger),n=yield this._dispatch(i,{queueId:"extensions"});return this._extensionEventBroadcaster.listen(),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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}clearExtensionCache(e){this._extensionMessenger.clearCacheByRegion(e)}postMessageToExtension(e,t){this._extensionMessenger.post(e,t)}handleExtensionCommand(e,t,i){return this._extensionMessenger.listenForCommand(e,t,i)}handleExtensionQuery(e,t,i){return this._extensionMessenger.listenForQuery(e,t,i)}_dispatch(e,t){return this._store.dispatch(e,t).then(()=>this.getState()).catch(e=>{throw this._errorTransformer.transform(e)})}};nv=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],nv);const rv=nv;function ov(e){return(...t)=>{const i=t.pop();return e(...t,(...e)=>{const t=i(...e);return"function"==typeof t?Pe(t):t})}}const av=ov(Fe),sv=ov(Re(Le,(e,t)=>Be(e,t)));class dv extends It{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 cv(e){return e.reduce((e,t)=>t?[...e,t]:e,[]).join(" ")}class lv extends It{constructor(e){super(e,{message:"The request has timed out or aborted."}),this.name="TimeoutError",this.type="timeout"}}class uv{constructor(){this._factoryMethods={},this.register("default",(e,t)=>new It(e,{message:t})),this.register("internal",(e,t)=>function(e,t){const{body:i}=e,{errors:n=[]}=i;return new It(e,{message:cv(n)||i.detail||i.title||t,errors:n.length?n.map(e=>({code:i.type,message:e})):[{code:i.type,message:i.detail||i.title}]})}(e,t)),this.register("storefront",(e,t)=>function(e,t){const{body:i}=e;return new It(e,{message:t||i.detail||i.title,errors:[{code:i.code||i.type,message:i.detail||i.title}]})}(e,t)),this.register("payment",(e,t)=>Zm(e,t)),this.register("timeout",e=>new lv(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=L(e.body.type.split("/"));return t&&this._factoryMethods[t]?t:"internal"}const t=L(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 hv(e,t){return Array.isArray(e)?e.map(e=>hv(e,t)):M(e)?Q(H(e,t),(e,i,n)=>{e[n]=hv(i,t)},{}):e}function pv(e,t){return function(e){return e.type===dt.ClearError}(t)?hv(e,e=>e===t.payload):e}function mv(e,t,i){return e===t||(e&&t&&"object"==typeof e&&"object"==typeof t?Array.isArray(e)&&Array.isArray(t)?function(e,t,i){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(!mv(e[n],t[n],i))return!1;return!0}(e,t,i):!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,i){const n=i&&i.keyFilter,r=n?Object.keys(e).filter(n):Object.keys(e),o=n?Object.keys(t).filter(n):Object.keys(t);if(r.length!==o.length)return!1;for(let n=0,o=r.length;n<o;n++){const o=r[n];if(!Object.prototype.hasOwnProperty.call(t,o))return!1;if(!mv(e[o],t[o],i))return!1}return!0}(e,t,i))):e===t)}function yv(e,t){return void 0===t||mv(e,t)?e:t}function gv(e,t,i){return e&&Object.prototype.hasOwnProperty.call(e,t)&&mv(e[t],i)?e:Object.assign(Object.assign({},e),{[t]:i})}const vv={errors:{},statuses:{}};function fv(e=vv,t){return d({data:Sv,errors:c(wv,pv),statuses:Iv})(e,t)}function Sv(e,t){var i,n;switch(t.type){case Ye.UpdateBillingAddressSucceeded:case Ye.ContinueAsGuestSucceeded:case Vt.LoadCheckoutSucceeded:return yv(e,t.payload&&t.payload.billingAddress);case Gt.HydrateInitialState:return yv(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.billingAddress);default:return e}}function wv(e=vv.errors,t){switch(t.type){case Vt.LoadCheckoutRequested:case Vt.LoadCheckoutSucceeded:return gv(e,"loadError",void 0);case Vt.LoadCheckoutFailed:return gv(e,"loadError",t.payload);case Ye.UpdateBillingAddressRequested:case Ye.UpdateBillingAddressSucceeded:return gv(e,"updateError",void 0);case Ye.UpdateBillingAddressFailed:return gv(e,"updateError",t.payload);case Sg.UpdateSubscriptionsRequested:case Sg.UpdateSubscriptionsSucceeded:case Ye.ContinueAsGuestRequested:case Ye.ContinueAsGuestSucceeded:return gv(e,"continueAsGuestError",void 0);case Sg.UpdateSubscriptionsFailed:case Ye.ContinueAsGuestFailed:return gv(e,"continueAsGuestError",t.payload);default:return e}}function Iv(e=vv.statuses,t){switch(t.type){case Vt.LoadCheckoutRequested:return gv(e,"isLoading",!0);case Vt.LoadCheckoutSucceeded:case Vt.LoadCheckoutFailed:return gv(e,"isLoading",!1);case Ye.UpdateBillingAddressRequested:return gv(e,"isUpdating",!0);case Ye.UpdateBillingAddressFailed:case Ye.UpdateBillingAddressSucceeded:return gv(e,"isUpdating",!1);case Ye.ContinueAsGuestRequested:case Sg.UpdateSubscriptionsRequested:return gv(e,"isContinuingAsGuest",!0);case Sg.UpdateSubscriptionsSucceeded:case Sg.UpdateSubscriptionsFailed:case Ye.ContinueAsGuestFailed:case Ye.ContinueAsGuestSucceeded:return gv(e,"isContinuingAsGuest",!1);default:return e}}const _v=function e(t,i,n){const{matchObject:r=(e,t)=>void 0!==e.id&&e.id===t.id}=n||{};if(!t)return i;if(!i||t===i)return t;let o=0,a=0;const s=(e,t,i)=>(o+=e===t?1:0,a+=e===i?1:0,e),d=i.map((i,n)=>{const o=t&&t[n];return Pg(o)&&Pg(i)?r(o,i)?s(Cv(o,i),o,i):s(yv(o,i),o,i):O(o)&&O(i)?s(e(o,i),o,i):s(yv(o,i),o,i)});return o===i.length&&t&&t.length===i.length?t:a===i.length?i:d},Cv=function e(t,i){return t?i&&t!==i?Object.keys(i).reduce((t,n)=>{const r=t[n],o=i[n];return Pg(r)&&Pg(o)?gv(t,n,e(r,o)):O(r)&&O(o)?gv(t,n,_v(r,o)):gv(t,n,o)},t):t:i},bv={errors:{},statuses:{}};function Pv(e=bv,t){return d({data:Ov,errors:c(Av,pv),statuses:Ev})(e,t)}function Ov(e,t){var i,n;switch(t.type){case Ye.UpdateBillingAddressSucceeded:case Vt.LoadCheckoutSucceeded:case cg.CreateConsignmentsSucceeded:case cg.DeleteConsignmentSucceeded:case cg.UpdateConsignmentSucceeded:case cg.UpdateShippingOptionSucceeded:case cg.LoadShippingOptionsSucceeded:case Pt.ApplyCouponSucceeded:case Pt.RemoveCouponSucceeded:case Tt.ApplyGiftCertificateSucceeded:case Tt.RemoveGiftCertificateSucceeded:return Cv(e,t.payload&&t.payload.cart);case Gt.HydrateInitialState:return Cv(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.cart);default:return e}}function Ev(e=bv.statuses,t){switch(t.type){case Vt.LoadCheckoutRequested:return gv(e,"isLoading",!0);case Vt.LoadCheckoutFailed:case Vt.LoadCheckoutSucceeded:return gv(e,"isLoading",!1);default:return e}}function Av(e=bv.errors,t){switch(t.type){case Vt.LoadCheckoutRequested:case Vt.LoadCheckoutSucceeded:return gv(e,"loadError",void 0);case Vt.LoadCheckoutFailed:return gv(e,"loadError",t.payload);default:return e}}var Tv;!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"}(Tv||(Tv={}));const kv={data:{},errors:{},statuses:{}},Dv={initializedContainers:{}},Mv={},zv={};function Nv(e=kv,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:xv}),errors:d({[t.meta.methodId]:Fv}),statuses:d({[t.meta.methodId]:Rv})})(e,t):e}function xv(e=Dv,t){switch(t.type){case Tv.InitializeButtonSucceeded:return t.meta&&t.meta.containerId?Cv(e,{initializedContainers:{[t.meta.containerId]:!0}}):e;case Tv.DeinitializeButtonSucceeded:return gv(e,"initializedContainers",{})}return e}function Fv(e=Mv,t){switch(t.type){case Tv.InitializeButtonRequested:case Tv.InitializeButtonSucceeded:return gv(e,"initializeError",void 0);case Tv.InitializeButtonFailed:return gv(e,"initializeError",t.payload);case Tv.DeinitializeButtonRequested:case Tv.DeinitializeButtonSucceeded:return gv(e,"deinitializeError",void 0);case Tv.DeinitializeButtonFailed:return gv(e,"deinitializeError",t.payload);default:return e}}function Rv(e=zv,t){switch(t.type){case Tv.InitializeButtonRequested:return gv(e,"isInitializing",!0);case Tv.InitializeButtonFailed:case Tv.InitializeButtonSucceeded:return gv(e,"isInitializing",!1);case Tv.DeinitializeButtonRequested:return gv(e,"isDeinitializing",!0);case Tv.DeinitializeButtonFailed:case Tv.DeinitializeButtonSucceeded:return gv(e,"isDeinitializing",!1);default:return e}}const Lv={meta:{},errors:{},statuses:{}};function Bv(e=Lv,t){return d({data:jv,errors:c(Uv,pv),statuses:qv})(e,t)}function jv(e,t){var i;switch(t.type){case ft.LoadConfigSucceeded:return Cv(e,t.payload);case Gt.HydrateInitialState:return Cv(e,null===(i=t.payload)||void 0===i?void 0:i.config);default:return e}}function Uv(e=Lv.errors,t){switch(t.type){case ft.LoadConfigSucceeded:return gv(e,"loadError",void 0);case ft.LoadConfigFailed:return gv(e,"loadError",t.payload);default:return e}}function qv(e=Lv.statuses,t){switch(t.type){case ft.LoadConfigRequested:return gv(e,"isLoading",!0);case ft.LoadConfigSucceeded:case ft.LoadConfigFailed:return gv(e,"isLoading",!1);default:return e}}const Vv={errors:{},statuses:{}};function Gv(e=Vv,t){return d({data:Hv,errors:c($v,pv),statuses:Wv})(e,t)}function Hv(e,t){var i,n;switch(t.type){case Vt.LoadCheckoutSucceeded:case Pt.ApplyCouponSucceeded:case cg.UpdateShippingOptionSucceeded:case Pt.RemoveCouponSucceeded:case wm.LoadOrderSucceeded:return _v(e,t.payload&&t.payload.coupons);case Gt.HydrateInitialState:return _v(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.coupons);default:return e}}function $v(e={},t){switch(t.type){case Pt.ApplyCouponRequested:case Pt.ApplyCouponSucceeded:return gv(e,"applyCouponError",void 0);case Pt.ApplyCouponFailed:return gv(e,"applyCouponError",t.payload);case Pt.RemoveCouponRequested:case Pt.RemoveCouponSucceeded:return gv(e,"removeCouponError",void 0);case Pt.RemoveCouponFailed:return gv(e,"removeCouponError",t.payload);default:return e}}function Wv(e={},t){switch(t.type){case Pt.ApplyCouponRequested:return gv(e,"isApplyingCoupon",!0);case Pt.ApplyCouponSucceeded:case Pt.ApplyCouponFailed:return gv(e,"isApplyingCoupon",!1);case Pt.RemoveCouponRequested:return gv(e,"isRemovingCoupon",!0);case Pt.RemoveCouponSucceeded:case Pt.RemoveCouponFailed:return gv(e,"isRemovingCoupon",!1);default:return e}}const Yv={errors:{},statuses:{}};function Kv(e=Yv,t){return d({data:Jv,errors:c(Zv,pv),statuses:Xv})(e,t)}function Jv(e,t){var i,n;switch(t.type){case Vt.LoadCheckoutSucceeded:case cg.CreateConsignmentsSucceeded:case cg.UpdateConsignmentSucceeded:case cg.DeleteConsignmentSucceeded:case cg.UpdateShippingOptionSucceeded:case Pt.ApplyCouponSucceeded:case Pt.RemoveCouponSucceeded:case Tt.ApplyGiftCertificateSucceeded:case Tt.RemoveGiftCertificateSucceeded:return _v(e,t.payload&&t.payload.giftCertificates);case Gt.HydrateInitialState:return _v(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.giftCertificates);default:return e}}function Zv(e=Yv.errors,t){switch(t.type){case Tt.ApplyGiftCertificateRequested:case Tt.ApplyGiftCertificateSucceeded:return gv(e,"applyGiftCertificateError",void 0);case Tt.ApplyGiftCertificateFailed:return gv(e,"applyGiftCertificateError",t.payload);case Tt.RemoveGiftCertificateRequested:case Tt.RemoveGiftCertificateSucceeded:return gv(e,"removeGiftCertificateError",void 0);case Tt.RemoveGiftCertificateFailed:return gv(e,"removeGiftCertificateError",t.payload);default:return e}}function Xv(e=Yv.statuses,t){switch(t.type){case Tt.ApplyGiftCertificateRequested:return gv(e,"isApplyingGiftCertificate",!0);case Tt.ApplyGiftCertificateSucceeded:case Tt.ApplyGiftCertificateFailed:return gv(e,"isApplyingGiftCertificate",!1);case Tt.RemoveGiftCertificateRequested:return gv(e,"isRemovingGiftCertificate",!0);case Tt.RemoveGiftCertificateSucceeded:case Tt.RemoveGiftCertificateFailed:return gv(e,"isRemovingGiftCertificate",!1);default:return e}}const Qv={errors:{},statuses:{}};function ef(e=Qv,t){return d({data:tf,errors:c(nf,pv),statuses:rf})(e,t)}function tf(e,t){var i,n;switch(t.type){case Ye.ContinueAsGuestSucceeded:case Vt.LoadCheckoutSucceeded:return Cv(e,t.payload&&t.payload.customer);case Dt.CreateCustomerAddressSucceeded:return Cv(e,t.payload);case Gt.HydrateInitialState:return Cv(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.customer);default:return e}}function nf(e=Qv.errors,t){switch(t.type){case Dt.CreateCustomerRequested:case Dt.CreateCustomerSucceeded:return gv(e,"createError",void 0);case Dt.CreateCustomerFailed:return gv(e,"createError",t.payload);case Dt.CreateCustomerAddressRequested:case Dt.CreateCustomerAddressSucceeded:return gv(e,"createAddressError",void 0);case Dt.CreateCustomerAddressFailed:return gv(e,"createAddressError",t.payload);default:return e}}function rf(e=Qv.statuses,t){switch(t.type){case Dt.CreateCustomerRequested:return gv(e,"isCreating",!0);case Dt.CreateCustomerFailed:case Dt.CreateCustomerSucceeded:return gv(e,"isCreating",!1);case Dt.CreateCustomerAddressRequested:return gv(e,"isCreatingAddress",!0);case Dt.CreateCustomerAddressFailed:case Dt.CreateCustomerAddressSucceeded:return gv(e,"isCreatingAddress",!1);default:return e}}const of={data:{},errors:{},statuses:{}};function af(e=of,t){return d({data:sf,errors:c(df,pv),statuses:cf})(e,t)}function sf(e=of.data,t){switch(t.type){case qt.InitializeSucceeded:return Cv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case qt.DeinitializeSucceeded:return Cv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function df(e=of.errors,t){switch(t.type){case qt.InitializeRequested:case qt.InitializeSucceeded:return Cv(e,{initializeErrors:Object.assign({},e.initializeErrors),initializeMethodId:e.initializeMethodId?e.initializeMethodId:void 0});case qt.InitializeFailed:return Cv(e,{initializeErrors:Object.assign(Object.assign({},e.initializeErrors),{[t.meta&&t.meta.methodId]:t.payload}),initializeMethodId:t.meta&&t.meta.methodId});case qt.DeinitializeRequested:case qt.DeinitializeSucceeded:return Cv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case qt.DeinitializeFailed:return Cv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case qt.SignInRequested:case qt.SignInSucceeded:return Cv(e,{signInError:void 0,signInMethodId:void 0});case qt.SignInFailed:return Cv(e,{signInError:t.payload,signInMethodId:t.meta&&t.meta.methodId});case qt.SignOutRequested:case qt.SignOutSucceeded:return Cv(e,{signOutError:void 0,signOutMethodId:void 0});case qt.SignOutFailed:return Cv(e,{signOutError:t.payload,signOutMethodId:t.meta&&t.meta.methodId});case qt.ExecutePaymentMethodCheckoutRequested:case qt.ExecutePaymentMethodCheckoutSucceeded:return Cv(e,{executePaymentMethodCheckoutError:void 0,executePaymentMethodCheckoutMethodId:void 0});case qt.ExecutePaymentMethodCheckoutFailed:return Cv(e,{executePaymentMethodCheckoutError:t.payload,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case qt.WidgetInteractionStarted:case qt.WidgetInteractionFinished:return Cv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case qt.WidgetInteractionFailed:return Cv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function cf(e=of.statuses,t){switch(t.type){case qt.InitializeRequested:return Cv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case qt.InitializeFailed:case qt.InitializeSucceeded:return Cv(e,{isInitializing:!1,initializeMethodId:void 0});case qt.DeinitializeRequested:return Cv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case qt.DeinitializeFailed:case qt.DeinitializeSucceeded:return Cv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case qt.SignInRequested:return Cv(e,{isSigningIn:!0,signInMethodId:t.meta&&t.meta.methodId});case qt.SignInFailed:case qt.SignInSucceeded:return Cv(e,{isSigningIn:!1,signInMethodId:void 0});case qt.SignOutRequested:return Cv(e,{isSigningOut:!0,signOutMethodId:t.meta&&t.meta.methodId});case qt.SignOutFailed:case qt.SignOutSucceeded:return Cv(e,{isSigningOut:!1,signOutMethodId:void 0});case qt.ExecutePaymentMethodCheckoutRequested:return Cv(e,{isExecutingPaymentMethodCheckout:!0,executePaymentMethodCheckoutMethodId:t.meta&&t.meta.methodId});case qt.ExecutePaymentMethodCheckoutFailed:case qt.ExecutePaymentMethodCheckoutSucceeded:return Cv(e,{isExecutingPaymentMethodCheckout:!1,executePaymentMethodCheckoutMethodId:void 0});case qt.WidgetInteractionStarted:return Cv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case qt.WidgetInteractionFinished:case qt.WidgetInteractionFailed:return Cv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const lf={errors:{},statuses:{}};function uf(e=lf,t){return d({data:hf,errors:c(pf,pv),statuses:mf})(e,t)}function hf(e,t){var i;return t.type===di.LoadExtensionsSucceeded?_v(e,t.payload):t.type===Gt.HydrateInitialState?_v(e,null===(i=t.payload)||void 0===i?void 0:i.extensions):e}function pf(e=lf.errors,t){switch(t.type){case di.LoadExtensionsRequested:case di.LoadExtensionsSucceeded:return gv(e,"loadError",void 0);case di.RenderExtensionRequested:case di.RenderExtensionSucceeded:return gv(e,"renderError",void 0);case di.LoadExtensionsFailed:return gv(e,"loadError",t.payload);case di.RenderExtensionFailed:return gv(e,"renderError",t.payload);default:return e}}function mf(e=lf.statuses,t){switch(t.type){case di.LoadExtensionsRequested:return gv(e,"isLoading",!0);case di.LoadExtensionsSucceeded:case di.LoadExtensionsFailed:return gv(e,"isLoading",!1);default:return e}}const yf={errors:{},statuses:{}};function gf(e=yf,t){return d({data:vf,errors:c(ff,pv),statuses:Sf})(e,t)}function vf(e,t){var i;switch(t.type){case ei.LoadFormFieldsSucceeded:return Cv(e,t.payload);case Gt.HydrateInitialState:return Cv(e,null===(i=t.payload)||void 0===i?void 0:i.formFields);default:return e}}function ff(e=yf.errors,t){switch(t.type){case ei.LoadFormFieldsSucceeded:return gv(e,"loadError",void 0);case ei.LoadFormFieldsFailed:return gv(e,"loadError",t.payload);default:return e}}function Sf(e=yf.statuses,t){switch(t.type){case ei.LoadFormFieldsRequested:return gv(e,"isLoading",!0);case ei.LoadFormFieldsSucceeded:case ei.LoadFormFieldsFailed:return gv(e,"isLoading",!1);default:return e}}const wf={errors:{},statuses:{}};function If(e=wf,t){return d({data:_f,errors:c(Cf,pv),statuses:bf})(e,t)}function _f(e,t){return t.type===Sm.LoadCountriesSucceeded?_v(e,t.payload):e}function Cf(e=wf.errors,t){switch(t.type){case Sm.LoadCountriesRequested:case Sm.LoadCountriesSucceeded:return gv(e,"loadError",void 0);case Sm.LoadCountriesFailed:return gv(e,"loadError",t.payload);default:return e}}function bf(e=wf.statuses,t){switch(t.type){case Sm.LoadCountriesRequested:return gv(e,"isLoading",!0);case Sm.LoadCountriesSucceeded:case Sm.LoadCountriesFailed:return gv(e,"isLoading",!1);default:return e}}const Pf={errors:{},meta:{},statuses:{}};function Of(e=Pf,t){return d({data:Ef,errors:c(Tf,pv),meta:Af,statuses:kf})(e,t)}function Ef(e,t){switch(t.type){case wm.LoadOrderSucceeded:case wm.LoadOrderPaymentsSucceeded:return Cv(e,G(t.payload,["billingAddress","coupons"]));default:return e}}function Af(e,t){switch(t.type){case wm.FinalizeOrderSucceeded:case wm.SubmitOrderSucceeded:return Cv(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 Tf(e=Pf.errors,t){switch(t.type){case wm.LoadOrderRequested:case wm.LoadOrderSucceeded:case wm.LoadOrderPaymentsSucceeded:case wm.LoadOrderPaymentsRequested:return gv(e,"loadError",void 0);case wm.LoadOrderFailed:case wm.LoadOrderPaymentsFailed:return gv(e,"loadError",t.payload);default:return e}}function kf(e=Pf.statuses,t){switch(t.type){case wm.LoadOrderRequested:case wm.LoadOrderPaymentsRequested:return gv(e,"isLoading",!0);case wm.LoadOrderSucceeded:case wm.LoadOrderFailed:case wm.LoadOrderPaymentsSucceeded:case wm.LoadOrderPaymentsFailed:return gv(e,"isLoading",!1);default:return e}}const Df={};function Mf(e=Df,t){return d({data:zf})(e,t)}function zf(e,t){switch(t.type){case wm.LoadOrderPaymentsSucceeded:case wm.LoadOrderSucceeded:return yv(e,t.payload&&t.payload.billingAddress);default:return e}}function Nf(e={},t){return d({data:xf})(e,t)}function xf(e,t){return t.type===ry.SubmitPaymentSucceeded?t.payload:e}const Ff={errors:{},statuses:{}};function Rf(e=Ff,t){return d({data:Lf,errors:c(jf,pv),meta:Bf,statuses:Uf})(e,t)}function Lf(e,t){switch(t.type){case Tm.LoadPaymentMethodSucceeded:return function(e,t,i){if(!t)return e;const n=W(t,"id"),r="object"==typeof i?Y(i):i||n,o=w(e,r),a=[...e];if(-1===o)a.push(t);else{const i=e[o];a[o]=Pg(i)&&Pg(t)?Cv(i,t):t}return a}(e||[],t.payload,t.payload&&{id:t.payload.id,gateway:t.payload.gateway});case Tm.LoadPaymentMethodsSucceeded:return _v(e,t.payload,{matchObject:(e,t)=>e.id===t.id&&e.gateway===t.gateway});default:return e}}function Bf(e,t){return t.type===Tm.LoadPaymentMethodsSucceeded?Cv(e,t.meta):e}function jf(e=Ff.errors,t){switch(t.type){case Tm.LoadPaymentMethodsRequested:case Tm.LoadPaymentMethodsSucceeded:return gv(e,"loadError",void 0);case Tm.LoadPaymentMethodsFailed:return gv(e,"loadError",t.payload);case Tm.LoadPaymentMethodRequested:case Tm.LoadPaymentMethodSucceeded:return Cv(e,{loadMethodId:void 0,loadMethodError:void 0});case Tm.LoadPaymentMethodFailed:return Cv(e,{loadMethodId:t.meta.methodId,loadMethodError:t.payload});default:return e}}function Uf(e=Ff.statuses,t){switch(t.type){case Tm.LoadPaymentMethodsRequested:return gv(e,"isLoading",!0);case Tm.LoadPaymentMethodsSucceeded:case Tm.LoadPaymentMethodsFailed:return gv(e,"isLoading",!1);case Tm.LoadPaymentMethodRequested:return Cv(e,{isLoadingMethod:!0,loadMethodId:t.meta.methodId});case Tm.LoadPaymentMethodSucceeded:case Tm.LoadPaymentMethodFailed:return Cv(e,{isLoadingMethod:!1,loadMethodId:void 0});default:return e}}const qf={data:{},errors:{},statuses:{}};function Vf(e=qf,t){return d({data:Gf,errors:c(Hf,pv),statuses:$f})(e,t)}function Gf(e=qf.data,t){switch(t.type){case Fm.InitializeSucceeded:if(t.meta){const{methodId:i,gatewayId:n}=t.meta,r=n?`${i}.${n}`:i;return Cv(e,{[r]:{isInitialized:!0}})}break;case Fm.DeinitializeSucceeded:if(t.meta){const{methodId:i,gatewayId:n}=t.meta,r=n?`${i}.${n}`:i;return Cv(e,{[r]:{isInitialized:!1}})}}return e}function Hf(e=qf.errors,t){switch(t.type){case Fm.InitializeRequested:case Fm.InitializeSucceeded:return Cv(e,{initializeError:void 0,initializeMethodId:void 0});case Fm.InitializeFailed:{let i=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:n}=t.meta;i=n?`${e}.${n}`:e}return Cv(e,{initializeError:t.payload,initializeMethodId:i})}case Fm.DeinitializeRequested:case Fm.DeinitializeSucceeded:return Cv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Fm.DeinitializeFailed:{let i=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:n}=t.meta;i=n?`${e}.${n}`:e}return Cv(e,{deinitializeError:t.payload,deinitializeMethodId:i})}case Fm.ExecuteRequested:case Fm.ExecuteSucceeded:return Cv(e,{executeError:void 0,executeMethodId:void 0});case Fm.ExecuteFailed:return Cv(e,{executeError:t.payload,executeMethodId:t.meta&&t.meta.methodId});case Fm.FinalizeRequested:case Fm.FinalizeSucceeded:return Cv(e,{finalizeError:void 0,finalizeMethodId:void 0});case Fm.FinalizeFailed:return Cv(e,{finalizeError:t.payload,finalizeMethodId:t.meta&&t.meta.methodId});case Fm.WidgetInteractionStarted:case Fm.WidgetInteractionFinished:return Cv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Fm.WidgetInteractionFailed:return Cv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta.methodId});default:return e}}function $f(e=qf.statuses,t){switch(t.type){case Fm.InitializeRequested:{let i=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:n}=t.meta;i=n?`${e}.${n}`:e}return Cv(e,{isInitializing:!0,initializeMethodId:i})}case Fm.InitializeFailed:case Fm.InitializeSucceeded:return Cv(e,{isInitializing:!1,initializeMethodId:void 0});case Fm.DeinitializeRequested:{let i=t.meta&&t.meta.methodId;if(t.meta){const{methodId:e,gatewayId:n}=t.meta;i=n?`${e}.${n}`:e}return Cv(e,{isDeinitializing:!0,deinitializeMethodId:i})}case Fm.DeinitializeFailed:case Fm.DeinitializeSucceeded:return Cv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Fm.ExecuteRequested:return Cv(e,{isExecuting:!0,executeMethodId:t.meta&&t.meta.methodId});case Fm.ExecuteFailed:case Fm.ExecuteSucceeded:return Cv(e,{isExecuting:!1,executeMethodId:void 0});case Fm.FinalizeRequested:return Cv(e,{isFinalizing:!0,finalizeMethodId:t.meta&&t.meta.methodId});case Fm.FinalizeFailed:case Fm.FinalizeSucceeded:return Cv(e,{isFinalizing:!1,finalizeMethodId:void 0});case Fm.WidgetInteractionStarted:return Cv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta.methodId});case Fm.WidgetInteractionFinished:case Fm.WidgetInteractionFailed:return Cv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const Wf={data:{}};function Yf(e=Wf,t){return d({data:Kf})(e,t)}function Kf(e=Wf.data,t){return t.type===tg.UpdatePaymentProviderCustomer?Cv(e,t.payload):e}const Jf={data:[],errors:{},statuses:{}};function Zf(e=Jf,t){return d({data:Xf,errors:c(eS,pv),meta:Qf,statuses:tS})(e,t)}function Xf(e=Jf.data,t){return t.type===kg.LoadInstrumentsSucceeded?_v(e,t.payload&&t.payload.vaultedInstruments||[]):e}function Qf(e,t){switch(t.type){case kg.LoadInstrumentsSucceeded:case kg.DeleteInstrumentSucceeded:return Cv(e,t.meta);default:return e}}function eS(e=Jf.errors,t){switch(t.type){case kg.LoadInstrumentsRequested:case kg.LoadInstrumentsSucceeded:return gv(e,"loadError",void 0);case kg.DeleteInstrumentRequested:case kg.DeleteInstrumentSucceeded:return Cv(e,{deleteError:void 0,failedInstrument:void 0});case kg.LoadInstrumentsFailed:return gv(e,"loadError",t.payload);case kg.DeleteInstrumentFailed:return Cv(e,{deleteError:t.payload,failedInstrument:t.meta.instrumentId});default:return e}}function tS(e=Jf.statuses,t){switch(t.type){case kg.LoadInstrumentsRequested:return gv(e,"isLoading",!0);case kg.DeleteInstrumentRequested:return Cv(e,{isDeleting:!0,deletingInstrument:t.meta.instrumentId});case kg.LoadInstrumentsSucceeded:case kg.LoadInstrumentsFailed:return gv(e,"isLoading",!1);case kg.DeleteInstrumentSucceeded:case kg.DeleteInstrumentFailed:return Cv(e,{isDeleting:!1,deletingInstrument:void 0});default:return e}}const iS={data:{}};function nS(e=iS,t){return t.meta&&t.meta.methodId?d({data:d({[t.meta.methodId]:rS})})(e,t):e}function rS(e,t){switch(t.type){case ig.InitializeRemoteBillingSucceeded:return gv(e,"billing",t.payload&&t.payload.billing);case ig.InitializeRemoteShippingSucceeded:return gv(e,"shipping",t.payload&&t.payload.shipping);case ig.LoadRemoteSettingsSucceeded:return gv(e,"settings",t.payload);case ig.UpdateRemoteCheckout:return Cv(e,t.payload);default:return e}}const oS={errors:{updateShippingOptionError:{},updateError:{},deleteError:{}},statuses:{isUpdating:{},isUpdatingShippingOption:{},isDeleting:{}}};function aS(e=oS,t){return d({data:sS,errors:c(dS,pv),statuses:cS})(e,t)}function sS(e,t){var i,n;switch(t.type){case Vt.LoadCheckoutSucceeded:case cg.LoadShippingOptionsSucceeded:case cg.CreateConsignmentsSucceeded:case cg.UpdateConsignmentSucceeded:case cg.DeleteConsignmentSucceeded:case cg.UpdateShippingOptionSucceeded:case Pt.ApplyCouponSucceeded:case Pt.RemoveCouponSucceeded:return _v(e,t.payload&&t.payload.consignments);case Dt.SignOutCustomerSucceeded:return _v(e,[]);case Gt.HydrateInitialState:return _v(e,null===(n=null===(i=t.payload)||void 0===i?void 0:i.checkout)||void 0===n?void 0:n.consignments);default:return e}}function dS(e=oS.errors,t){switch(t.type){case Vt.LoadCheckoutRequested:case Vt.LoadCheckoutSucceeded:case cg.LoadShippingOptionsSucceeded:case cg.LoadShippingOptionsRequested:return gv(e,"loadError",void 0);case Vt.LoadCheckoutFailed:case cg.LoadShippingOptionsFailed:return gv(e,"loadError",t.payload);case cg.CreateConsignmentsRequested:case cg.CreateConsignmentsSucceeded:return gv(e,"createError",void 0);case cg.CreateConsignmentsFailed:return gv(e,"createError",t.payload);case cg.UpdateConsignmentSucceeded:case cg.UpdateConsignmentRequested:return t.meta?Cv(e,{updateError:{[t.meta.id]:void 0}}):e;case cg.UpdateConsignmentFailed:return t.meta?Cv(e,{updateError:{[t.meta.id]:t.payload}}):e;case cg.DeleteConsignmentSucceeded:case cg.DeleteConsignmentRequested:return t.meta?Cv(e,{deleteError:{[t.meta.id]:void 0}}):e;case cg.DeleteConsignmentFailed:return t.meta?Cv(e,{deleteError:{[t.meta.id]:t.payload}}):e;case cg.UpdateShippingOptionRequested:case cg.UpdateShippingOptionSucceeded:return t.meta?Cv(e,{updateShippingOptionError:{[t.meta.id]:void 0}}):e;case cg.UpdateShippingOptionFailed:return t.meta?Cv(e,{updateShippingOptionError:{[t.meta.id]:t.payload}}):e;default:return e}}function cS(e=oS.statuses,t){switch(t.type){case Vt.LoadCheckoutRequested:return gv(e,"isLoading",!0);case cg.LoadShippingOptionsRequested:return gv(e,"isLoadingShippingOptions",!0);case Vt.LoadCheckoutSucceeded:case Vt.LoadCheckoutFailed:return gv(e,"isLoading",!1);case cg.LoadShippingOptionsSucceeded:case cg.LoadShippingOptionsFailed:return gv(e,"isLoadingShippingOptions",!1);case cg.CreateConsignmentsRequested:return gv(e,"isCreating",!0);case cg.CreateConsignmentsSucceeded:case cg.CreateConsignmentsFailed:return gv(e,"isCreating",!1);case cg.UpdateConsignmentRequested:return t.meta?Cv(e,{isUpdating:{[t.meta.id]:!0}}):e;case cg.UpdateConsignmentSucceeded:case cg.UpdateConsignmentFailed:return t.meta?Cv(e,{isUpdating:{[t.meta.id]:!1}}):e;case cg.DeleteConsignmentRequested:return t.meta?Cv(e,{isDeleting:{[t.meta.id]:!0}}):e;case cg.DeleteConsignmentSucceeded:case cg.DeleteConsignmentFailed:return t.meta?Cv(e,{isDeleting:{[t.meta.id]:!1}}):e;case cg.UpdateShippingOptionRequested:return t.meta?Cv(e,{isUpdatingShippingOption:{[t.meta.id]:!0}}):e;case cg.UpdateShippingOptionSucceeded:case cg.UpdateShippingOptionFailed:return t.meta?Cv(e,{isUpdatingShippingOption:{[t.meta.id]:!1}}):e;default:return e}}function lS(e,t){const i={};return Object.keys(e).forEach(n=>{const r=e[n],o=t?`${t}.${n}`:n;"object"==typeof r?Object.assign(i,lS(r,o)):i[o]=r}),i}function uS(e){return Object.keys(e).sort().reduce((t,i)=>Object.assign(Object.assign({},t),{[i]:e[i]}),{})}const hS={errors:{},statuses:{}};function pS(e=hS,t){return d({data:mS,errors:c(yS,pv),statuses:gS})(e,t)}function mS(e,t){if(t.type!==Fg.LoadPickupOptionsSucceeded)return e;if(t.meta){const i=uS(lS({consignmentId:t.meta.consignmentId,searchArea:t.meta.searchArea}));return gv(e,btoa(`${JSON.stringify(i)}`),t.payload)}}function yS(e=hS.errors,t){switch(t.type){case Fg.LoadPickupOptionsRequested:case Fg.LoadPickupOptionsSucceeded:return gv(e,"loadError",void 0);case Fg.LoadPickupOptionsFailed:return gv(e,"loadError",t.payload);default:return e}}function gS(e=hS.statuses,t){switch(t.type){case Fg.LoadPickupOptionsRequested:return gv(e,"isLoading",!0);case Fg.LoadPickupOptionsSucceeded:case Fg.LoadPickupOptionsFailed:return gv(e,"isLoading",!1);default:return e}}const vS={errors:{},statuses:{}};function fS(e=vS,t){return d({data:SS,errors:c(wS,pv),statuses:IS})(e,t)}function SS(e,t){return t.type===yg.LoadShippingCountriesSucceeded?_v(e,t.payload):e}function wS(e=vS.errors,t){switch(t.type){case yg.LoadShippingCountriesRequested:case yg.LoadShippingCountriesSucceeded:return gv(e,"loadError",void 0);case yg.LoadShippingCountriesFailed:return gv(e,"loadError",t.payload);default:return e}}function IS(e=vS.statuses,t){switch(t.type){case yg.LoadShippingCountriesRequested:return gv(e,"isLoading",!0);case yg.LoadShippingCountriesSucceeded:case yg.LoadShippingCountriesFailed:return gv(e,"isLoading",!1);default:return e}}const _S={data:{},errors:{},statuses:{}};function CS(e=_S,t){return d({data:bS,errors:c(PS,pv),statuses:OS})(e,t)}function bS(e=_S.data,t){switch(t.type){case Rg.InitializeSucceeded:return Cv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!0}});case Rg.DeinitializeSucceeded:return Cv(e,{[t.meta&&t.meta.methodId]:{isInitialized:!1}})}return e}function PS(e=_S.errors,t){switch(t.type){case Rg.InitializeRequested:case Rg.InitializeSucceeded:return Cv(e,{initializeError:void 0,initializeMethodId:void 0});case Rg.InitializeFailed:return Cv(e,{initializeError:t.payload,initializeMethodId:t.meta&&t.meta.methodId});case Rg.DeinitializeRequested:case Rg.DeinitializeSucceeded:return Cv(e,{deinitializeError:void 0,deinitializeMethodId:void 0});case Rg.DeinitializeFailed:return Cv(e,{deinitializeError:t.payload,deinitializeMethodId:t.meta&&t.meta.methodId});case Rg.UpdateAddressRequested:case Rg.UpdateAddressSucceeded:return Cv(e,{updateAddressError:void 0,updateAddressMethodId:void 0});case Rg.UpdateAddressFailed:return Cv(e,{updateAddressError:t.payload,updateAddressMethodId:t.meta&&t.meta.methodId});case Rg.SelectOptionRequested:case Rg.SelectOptionSucceeded:return Cv(e,{selectOptionError:void 0,selectOptionMethodId:void 0});case Rg.SelectOptionFailed:return Cv(e,{selectOptionError:t.payload,selectOptionMethodId:t.meta&&t.meta.methodId});case Rg.WidgetInteractionStarted:case Rg.WidgetInteractionFinished:return Cv(e,{widgetInteractionError:void 0,widgetInteractionMethodId:void 0});case Rg.WidgetInteractionFailed:return Cv(e,{widgetInteractionError:t.payload,widgetInteractionMethodId:t.meta&&t.meta.methodId});default:return e}}function OS(e=_S.statuses,t){switch(t.type){case Rg.InitializeRequested:return Cv(e,{isInitializing:!0,initializeMethodId:t.meta&&t.meta.methodId});case Rg.InitializeFailed:case Rg.InitializeSucceeded:return Cv(e,{isInitializing:!1,initializeMethodId:void 0});case Rg.DeinitializeRequested:return Cv(e,{isDeinitializing:!0,deinitializeMethodId:t.meta&&t.meta.methodId});case Rg.DeinitializeFailed:case Rg.DeinitializeSucceeded:return Cv(e,{isDeinitializing:!1,deinitializeMethodId:void 0});case Rg.UpdateAddressRequested:return Cv(e,{isUpdatingAddress:!0,updateAddressMethodId:t.meta&&t.meta.methodId});case Rg.UpdateAddressFailed:case Rg.UpdateAddressSucceeded:return Cv(e,{isUpdatingAddress:!1,updateAddressMethodId:void 0});case Rg.SelectOptionRequested:return Cv(e,{isSelectingOption:!0,selectOptionMethodId:t.meta&&t.meta.methodId});case Rg.SelectOptionFailed:case Rg.SelectOptionSucceeded:return Cv(e,{isSelectingOption:!1,selectOptionMethodId:void 0});case Rg.WidgetInteractionStarted:return Cv(e,{isWidgetInteracting:!0,widgetInteractionMethodId:t.meta&&t.meta.methodId});case Rg.WidgetInteractionFinished:case Rg.WidgetInteractionFailed:return Cv(e,{isWidgetInteracting:!1,widgetInteractionMethodId:void 0});default:return e}}const ES={errors:{},statuses:{}};function AS(e=ES,t){return d({data:TS,errors:c(kS,pv),statuses:DS})(e,t)}function TS(e,t){return t.type===Xg.SendSignInEmailSucceeded?Cv(e,t.payload):e}function kS(e=ES.errors,t){switch(t.type){case Xg.SendSignInEmailRequested:case Xg.SendSignInEmailSucceeded:return gv(e,"sendError",void 0);case Xg.SendSignInEmailFailed:return gv(e,"sendError",t.payload);default:return e}}function DS(e=ES.statuses,t){switch(t.type){case Xg.SendSignInEmailRequested:return gv(e,"isSending",!0);case Xg.SendSignInEmailFailed:case Xg.SendSignInEmailSucceeded:return gv(e,"isSending",!1);default:return e}}const MS={errors:{},statuses:{}};function zS(e=MS,t){return d({errors:c(NS,pv),statuses:xS})(e,t)}function NS(e=MS.errors,t){switch(t.type){case gg.ApplyStoreCreditRequested:case gg.ApplyStoreCreditSucceeded:return gv(e,"applyError",void 0);case gg.ApplyStoreCreditFailed:return gv(e,"applyError",t.payload);default:return e}}function xS(e=MS.statuses,t){switch(t.type){case gg.ApplyStoreCreditRequested:return gv(e,"isApplying",!0);case gg.ApplyStoreCreditSucceeded:case gg.ApplyStoreCreditFailed:return gv(e,"isApplying",!1);default:return e}}const FS={errors:{},statuses:{}};function RS(e=FS,t){return d({errors:c(LS,pv),statuses:BS})(e,t)}function LS(e=FS.errors,t){switch(t.type){case Sg.UpdateSubscriptionsRequested:case Sg.UpdateSubscriptionsSucceeded:return gv(e,"updateError",void 0);case Sg.UpdateSubscriptionsFailed:return gv(e,"updateError",t.payload);default:return e}}function BS(e=FS.statuses,t){switch(t.type){case Sg.UpdateSubscriptionsRequested:return gv(e,"isUpdating",!0);case Sg.UpdateSubscriptionsFailed:case Sg.UpdateSubscriptionsSucceeded:return gv(e,"isUpdating",!1);default:return e}}const jS={errors:{},statuses:{}};function US(e=jS,t){return d({data:qS,errors:c(VS,pv),statuses:GS})(e,t)}function qS(e,t){var i;switch(t.type){case Vt.LoadCheckoutSucceeded:case Vt.UpdateCheckoutSucceeded:case gg.ApplyStoreCreditSucceeded:case Ye.UpdateBillingAddressSucceeded:case Pt.ApplyCouponSucceeded:case Pt.RemoveCouponSucceeded:case cg.CreateConsignmentsSucceeded:case cg.UpdateConsignmentSucceeded:case cg.DeleteConsignmentSucceeded:case cg.UpdateShippingOptionSucceeded:case cg.LoadShippingOptionsSucceeded:case Tt.ApplyGiftCertificateSucceeded:case Tt.RemoveGiftCertificateSucceeded:case ii.VerifyCheckoutSucceeded:return Cv(e,G(t.payload,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));case wm.SubmitOrderSucceeded:return gv(e,"orderId",t.payload&&t.payload.order.orderId);case Gt.HydrateInitialState:return Cv(e,G(null===(i=t.payload)||void 0===i?void 0:i.checkout,["billingAddress","cart","consignments","customer","coupons","giftCertificates"]));default:return e}}function VS(e=jS.errors,t){switch(t.type){case Vt.LoadCheckoutRequested:case Vt.LoadCheckoutSucceeded:return gv(e,"loadError",void 0);case Vt.LoadCheckoutFailed:return gv(e,"loadError",t.payload);case Vt.UpdateCheckoutRequested:case Vt.UpdateCheckoutSucceeded:return gv(e,"updateError",void 0);case Vt.UpdateCheckoutFailed:return gv(e,"updateError",t.payload);default:return e}}function GS(e=jS.statuses,t){switch(t.type){case Vt.LoadCheckoutRequested:return gv(e,"isLoading",!0);case Vt.LoadCheckoutFailed:case Vt.LoadCheckoutSucceeded:return gv(e,"isLoading",!1);case Vt.UpdateCheckoutRequested:return gv(e,"isUpdating",!0);case Vt.UpdateCheckoutFailed:case Vt.UpdateCheckoutSucceeded:return gv(e,"isUpdating",!1);case ii.ExecuteRequested:return gv(e,"isExecutingSpamCheck",!0);case ii.ExecuteFailed:case ii.ExecuteSucceeded:return gv(e,"isExecutingSpamCheck",!1);default:return e}}function HS(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}function $S(e){return function(e){const t=Object.create(e);return function(e,t){let i=Object.getPrototypeOf(e);for(;i;)t(i),i=Object.getPrototypeOf(i)}(e,i=>{Object.getOwnPropertyNames(i).forEach(i=>{"constructor"!==i&&"function"==typeof t[i]&&"_"!==i.charAt(0)&&(t[i]=((e,t)=>(...i)=>p(e[t].call(e,...i)))(e,i))})}),t}(e)}const WS={"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"},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 YS(e){return Y({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},b)}const KS={errors:{},statuses:{}};function JS(){const e=function(){const e=av(e=>e.data,e=>()=>e),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingBillingAddress))),i=av(e=>e.errors.updateError,e=>()=>e),n=av(e=>e.errors.continueAsGuestError,e=>()=>e),r=av(e=>e.errors.loadError,e=>()=>e),o=av(e=>!!e.statuses.isUpdating,e=>()=>e),a=av(e=>!!e.statuses.isContinuingAsGuest,e=>()=>e),s=av(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((d=vv)=>({getBillingAddress:e(d),getBillingAddressOrThrow:t(d),getUpdateError:i(d),getContinueAsGuestError:n(d),getLoadError:r(d),isUpdating:o(d),isContinuingAsGuest:a(d),isLoading:s(d)}))}(),t=function(){const e=av(e=>e.data,e=>()=>e),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingCart))),i=av(e=>e.errors.loadError,e=>()=>e),n=av(e=>!!e.statuses.isLoading,e=>()=>e),r=av(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.locale},e=>()=>e);return Oe((o=bv)=>({getCart:e(o),getCartOrThrow:t(o),getLoadError:i(o),isLoading:n(o),getLocale:r(o)}))}(),i=function(){const e=av(e=>e,e=>()=>e),t=av(e=>e.statuses,e=>Pe(t=>{if(t){const i=e[t];return!0===(i&&i.isInitializing)}return Z(e,{isInitializing:!0})})),i=av(e=>e.data,e=>Pe((t,i)=>{const n=e[t];return!!n&&(i?!0===n.initializedContainers[i]:Z(n.initializedContainers,e=>!0===e))})),n=av(e=>e.statuses,e=>Pe(t=>{if(t){const i=e[t];return!0===(i&&i.isDeinitializing)}return Z(e,{isDeinitializing:!0})})),r=av(e=>e.errors,e=>Pe(t=>{const i=t?e[t]:S(ne(e),e=>!(!e||!e.initializeError));return i&&i.initializeError})),o=av(e=>e.errors,e=>Pe(t=>{const i=t?e[t]:S(ne(e),e=>!(!e||!e.deinitializeError));return i&&i.deinitializeError}));return Oe((a=kv)=>({getState:e(a),isInitializing:t(a),isInitialized:i(a),isDeinitializing:n(a),getInitializeError:r(a),getDeinitializeError:o(a)}))}(),n=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.data,e=>t=>{if(!e)return;const{flashMessages:i}=e.context;return i?void 0!==t?i.filter(({type:e})=>t===e):i:void 0}),i=av(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),n=av(i,e=>()=>HS(e(),()=>new Xe(We.MissingCheckoutConfig))),r=av(e=>e.data&&e.data.context,e=>()=>e),o=av(e=>e.meta&&e.meta.externalSource,e=>()=>e),a=av(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.host},e=>()=>e),s=av(e=>{var t;return null===(t=e.meta)||void 0===t?void 0:t.locale},e=>()=>e),d=av(e=>e.meta&&e.meta.variantIdentificationToken,e=>()=>e),c=av(e=>e.errors.loadError,e=>()=>e),l=av(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((u=Lv,h)=>({getConfig:e(u),getFlashMessages:t(u),getStoreConfig:i(u,{formState:h}),getStoreConfigOrThrow:n(u,{formState:h}),getContextConfig:r(u),getExternalSource:o(u),getHost:a(u),getLocale:s(u),getVariantIdentificationToken:d(u),getLoadError:c(u),isLoading:l(u)}))}(),r=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.errors.loadError,e=>()=>e),i=av(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((n=wf)=>({getCountries:e(n),getLoadError:t(n),isLoading:i(n)}))}(),o=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.errors.removeCouponError,e=>()=>e),i=av(e=>e.errors.applyCouponError,e=>()=>e),n=av(e=>!!e.statuses.isApplyingCoupon,e=>()=>e),r=av(e=>!!e.statuses.isRemovingCoupon,e=>()=>e);return Oe((o=Vv)=>({getCoupons:e(o),getRemoveError:t(o),getApplyError:i(o),isApplying:n(o),isRemoving:r(o)}))}(),a=function(){const e=av(e=>e.data,e=>()=>e),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingCustomer))),i=av(e=>e.errors.createError,e=>()=>e),n=av(e=>!!e.statuses.isCreating,e=>()=>e),r=av(e=>e.errors.createAddressError,e=>()=>e),o=av(e=>!!e.statuses.isCreatingAddress,e=>()=>e);return Oe((a=Qv)=>({getCustomer:e(a),getCustomerOrThrow:t(a),getCreateAccountError:i(a),isCreatingCustomerAccount:n(a),getCreateAddressError:r(a),isCreatingCustomerAddress:o(a)}))}(),s=function(){const e=av(e=>e.errors.signInMethodId,e=>e.errors.signInError,(e,t)=>i=>{if(!i||e===i)return t}),t=av(e=>e.errors.signOutMethodId,e=>e.errors.signOutError,(e,t)=>i=>{if(!i||e===i)return t}),i=av(e=>e.errors.executePaymentMethodCheckoutMethodId,e=>e.errors.executePaymentMethodCheckoutError,(e,t)=>i=>{if(!i||e===i)return t}),n=av(e=>e.errors.initializeMethodId,e=>e.errors.initializeErrors,(e,t)=>i=>{if(e&&t)return i?t[i]:t[e]}),r=av(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>i=>{if(!i||e===i)return t}),o=av(e=>e.statuses.signInMethodId,e=>e.statuses.isSigningIn,(e,t)=>i=>!(i&&e!==i||!t)),a=av(e=>e.statuses.signOutMethodId,e=>e.statuses.isSigningOut,(e,t)=>i=>!(i&&e!==i||!t)),s=av(e=>e.statuses.executePaymentMethodCheckoutMethodId,e=>e.statuses.isExecutingPaymentMethodCheckout,(e,t)=>i=>!(i&&e!==i||!t)),d=av(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>i=>!(i&&e!==i||!t)),c=av(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),l=av(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>i=>!(i&&e!==i||!t));return Oe((u=of)=>({getSignInError:e(u),getSignOutError:t(u),getExecutePaymentMethodCheckoutError:i(u),getInitializeError:n(u),getWidgetInteractionError:r(u),isSigningIn:o(u),isSigningOut:a(u),isExecutingPaymentMethodCheckout:s(u),isInitializing:d(u),isInitialized:c(u),isWidgetInteracting:l(u)}))}(),d=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.errors.removeGiftCertificateError,e=>()=>e),i=av(e=>e.errors.applyGiftCertificateError,e=>()=>e),n=av(e=>!!e.statuses.isApplyingGiftCertificate,e=>()=>e),r=av(e=>!!e.statuses.isRemovingGiftCertificate,e=>()=>e);return Oe((o=Yv)=>({getGiftCertificates:e(o),getRemoveError:t(o),getApplyError:i(o),isApplying:n(o),isRemoving:r(o)}))}(),c=function(){const e=av(e=>e.data,e=>t=>{if(!e)return;const i=t.gateway?`${t.gateway}.${t.id}`:t.id,n=WS[i];return n?f(e,n):[]}),t=av(e=>e.data,(e=[])=>t=>{const i=ne(WS);return e.find(e=>e.bigpayToken===t&&"card"===e.type&&i.some(t=>T(e,t)))}),i=av(t,e=>t=>HS(e(t),()=>new Xe(We.MissingPaymentInstrument))),n=av(e=>e.data,e=>()=>{if(e)return I(WS,t=>f(e,e=>T(e,t)))}),r=av(e=>e.meta,e=>()=>e),o=av(e=>e.errors.loadError,e=>()=>e),a=av(e=>e.errors.failedInstrument,e=>e.errors.deleteError,(e,t)=>i=>{if(!i||e===i)return t}),s=av(e=>e.statuses.isLoading,e=>()=>!!e),d=av(e=>e.statuses.deletingInstrument,e=>e.statuses.isDeleting,(e,t)=>i=>!(i&&e!==i||!t));return Oe((c=Jf)=>({getCardInstrument:t(c),getCardInstrumentOrThrow:i(c),getInstruments:n(c),getInstrumentsByPaymentMethod:e(c),getInstrumentsMeta:r(c),getLoadError:o(c),getDeleteError:a(c),isLoading:s(c),isDeleting:d(c)}))}(),l=function(){const e=av(e=>e.data,e=>(t=[],i)=>{const n=S(t,{code:i});return(e?e.shippingAddress:[]).map(e=>o(e,t,n))}),t=av(e=>e.data,e=>(t=[],i)=>{const n=S(t,{code:i});return(e?e.billingAddress:[]).map(e=>o(e,t,n))}),i=av(e=>e.data,e=>()=>e?e.customerAccount:[]),n=av(e=>e.errors.loadError,e=>()=>e),r=av(e=>!!e.statuses.isLoading,e=>()=>e);function o(e,t,i){return"countryCode"===e.name?function(e,t=[],i){if(!t.length)return e;const{code:n=""}=i||{},r=t.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{options:{items:r},default:n,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,t,i):"stateOrProvince"===e.name?function(e,t){const{subdivisions:i=[],requiresState:n}=t||{};if(!i.length)return Object.assign(Object.assign({},e),{required:null!=n&&n});const r=i.map(({code:e,name:t})=>({value:e,label:t}));return Object.assign(Object.assign({},e),{name:"stateOrProvinceCode",options:{items:r},required:null==n||n,type:"array",fieldType:"dropdown",itemtype:"string"})}(e,i):"postalCode"===e.name?function(e,t){const{hasPostalCodes:i=[]}=t||{};return void 0===i?e:Object.assign(Object.assign({},e),{required:Boolean(i)})}(e,i):e}return Oe((o=yf)=>({getShippingAddressFields:e(o),getBillingAddressFields:t(o),getCustomerAccountFields:i(o),getLoadError:n(o),isLoading:r(o)}))}(),u=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.meta,e=>()=>e),i=av(e=>e.data,e=>(t,i)=>S(e,i?{id:t,gateway:i}:{id:t})),n=av(i,e=>(t,i)=>HS(e(t,i),()=>new Xe(We.MissingPaymentMethod))),r=av(e=>e.errors.loadError,e=>()=>e),o=av(e=>e.errors.loadMethodId,e=>e.errors.loadMethodError,(e,t)=>i=>{if(!i||e===i)return t}),a=av(e=>e.statuses.isLoading,e=>()=>!!e),s=av(e=>e.statuses.loadMethodId,e=>e.statuses.isLoadingMethod,(e,t)=>i=>!(i&&e!==i||!t));return Oe((d=Ff)=>({getPaymentMethods:e(d),getPaymentMethodsMeta:t(d),getPaymentMethod:i(d),getPaymentMethodOrThrow:n(d),getLoadError:r(d),getLoadMethodError:o(d),isLoading:a(d),isLoadingMethod:s(d)}))}(),h=function(){const e=av(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>i=>{if(!i||e===i)return t}),t=av(e=>e.errors.executeMethodId,e=>e.errors.executeError,(e,t)=>i=>{if(!i||e===i)return t}),i=av(e=>e.errors.finalizeMethodId,e=>e.errors.finalizeError,(e,t)=>i=>{if(!i||e===i)return t}),n=av(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>i=>{if(!i||e===i)return t}),r=av(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>i=>!(i&&e!==i||!t)),o=av(e=>e.data,e=>t=>{const i=t.gatewayId?`${t.methodId}.${t.gatewayId}`:t.methodId;return!(!e[i]||!e[i].isInitialized)}),a=av(e=>e.statuses.executeMethodId,e=>e.statuses.isExecuting,(e,t)=>i=>!(i&&e!==i||!t)),s=av(e=>e.statuses.finalizeMethodId,e=>e.statuses.isFinalizing,(e,t)=>i=>!(i&&e!==i||!t)),d=av(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>i=>!(i&&e!==i||!t));return Oe((c=qf)=>({getInitializeError:e(c),getExecuteError:t(c),getFinalizeError:i(c),getWidgetInteractingError:n(c),isInitializing:r(c),isInitialized:o(c),isExecuting:a(c),isFinalizing:s(c),isWidgetInteracting:d(c)}))}(),p=function(){const e=av(e=>e.data,e=>(t,i)=>{if(!e)return;const n=uS(lS({consignmentId:t,searchArea:i})),r=btoa(`${JSON.stringify(n)}`);return e[r]}),t=av(e=>e.errors.loadError,e=>()=>e),i=av(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((n=hS)=>({getPickupOptions:e(n),getLoadError:t(n),isLoading:i(n)}))}(),m=function(){const e=av(e=>e.data,e=>()=>e),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingPaymentProviderCustomer)));return Oe((i=Wf)=>({getPaymentProviderCustomer:e(i),getPaymentProviderCustomerOrThrow:t(i)}))}(),y=function(){const e=av(e=>e.data,e=>t=>e[t]);return Oe((t=iS)=>({getCheckout:e(t)}))}(),g=function(){const e=av(e=>e.data,e=>()=>{const t=null==e?void 0:e.find(e=>!e.selectedPickupOption);return null==t?void 0:t.shippingAddress}),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingShippingAddress))),i=av(e=>e.data,e=>()=>{const t=null==e?void 0:e.filter(e=>!e.selectedPickupOption);return t?t.map(e=>e.shippingAddress):[]}),n=av(i,e=>()=>HS(e(),()=>new Xe(We.MissingShippingAddress)));return Oe((r=oS)=>({getShippingAddress:e(r),getShippingAddressOrThrow:t(r),getShippingAddresses:i(r),getShippingAddressesOrThrow:n(r)}))}(),v=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.errors.loadError,e=>()=>e),i=av(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((n=vS)=>({getShippingCountries:e(n),getLoadError:t(n),isLoading:i(n)}))}(),w=function(){const e=av(e=>e.errors.updateAddressMethodId,e=>e.errors.updateAddressError,(e,t)=>i=>{if(!i||e===i)return t}),t=av(e=>e.errors.selectOptionMethodId,e=>e.errors.selectOptionError,(e,t)=>i=>{if(!i||e===i)return t}),i=av(e=>e.errors.initializeMethodId,e=>e.errors.initializeError,(e,t)=>i=>{if(!i||e===i)return t}),n=av(e=>e.errors.widgetInteractionMethodId,e=>e.errors.widgetInteractionError,(e,t)=>i=>{if(!i||e===i)return t}),r=av(e=>e.statuses.updateAddressMethodId,e=>e.statuses.isUpdatingAddress,(e,t)=>i=>!(i&&e!==i||!t)),o=av(e=>e.statuses.selectOptionMethodId,e=>e.statuses.isSelectingOption,(e,t)=>i=>!(i&&e!==i||!t)),a=av(e=>e.statuses.initializeMethodId,e=>e.statuses.isInitializing,(e,t)=>i=>!(i&&e!==i||!t)),s=av(e=>e.data,e=>t=>!(!e[t]||!e[t].isInitialized)),d=av(e=>e.statuses.widgetInteractionMethodId,e=>e.statuses.isWidgetInteracting,(e,t)=>i=>!(i&&e!==i||!t));return Oe((c=_S)=>({getUpdateAddressError:e(c),getSelectOptionError:t(c),getInitializeError:i(c),getWidgetInteractionError:n(c),isUpdatingAddress:r(c),isSelectingOption:o(c),isInitializing:a(c),isInitialized:s(c),isWidgetInteracting:d(c)}))}(),_=function(){const e=av(e=>e.data,e=>()=>e),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingConsignments))),i=av(e=>e.data,e=>t=>{if(e&&e.length)return S(e,{id:t})}),n=av(e=>e.data,e=>t=>{if(e&&e.length)return S(e,e=>{return i=e.shippingAddress,n=t,A(YS(i),YS(n));var i,n})}),r=av(e=>e.data,e=>()=>{if(e&&e.length)return e[0].selectedShippingOption}),o=av(e=>e.errors.loadError,e=>()=>e),a=av(e=>e.errors.createError,e=>()=>e),s=av(e=>e.errors.loadShippingOptionsError,e=>()=>e),d=av(e,(e,{cart:t})=>t.getCart,(e,t)=>()=>{const i=t();if(!i)return[];const n=(e()||[]).reduce((e,t)=>e.concat(t.lineItemIds),[]);return(i.lineItems.physicalItems||[]).filter(e=>n.indexOf(e.id)<0)}),c=av(e=>e.errors.updateError,e=>t=>t?e[t]:S(e)),l=av(e=>e.errors.deleteError,e=>t=>t?e[t]:S(e)),u=av(n,c,a,(e,t,i)=>n=>{const r=e(n);return r?t(r.id):i()}),h=av(e=>e.errors.updateShippingOptionError,e=>t=>t?e[t]:S(e)),p=av(e=>e.statuses.isLoading,e=>()=>!0===e),m=av(e=>e.statuses.isLoadingShippingOptions,e=>()=>!0===e),y=av(e=>e.statuses.isCreating,e=>()=>!0===e),g=av(e=>e.statuses.isUpdating,e=>t=>t?!0===e[t]:!0===S(e)),v=av(e=>e.statuses.isDeleting,e=>t=>t?!0===e[t]:!0===S(e)),f=av(n,g,y,(e,t,i)=>n=>{const r=e(n);return r?t(r.id):i()}),w=av(e=>e.statuses.isUpdatingShippingOption,e=>t=>t?!0===e[t]:!0===S(e));return Oe((S=oS,I)=>({getConsignments:e(S),getConsignmentsOrThrow:t(S),getConsignmentById:i(S),getConsignmentByAddress:n(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:v(S),isAssigningItems:f(S),isUpdatingShippingOption:w(S)}))}(),C=function(){const e=av(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,i,n,r,o,a)=>()=>{const s=t(),d=i(),c=n(),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=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingCheckout))),i=av(e,e=>t=>{const i=e();if(!i)return;const n=i.grandTotal||0,r=i.customer.storeCredit||0;return t?Math.max(n-r,0):i.outstandingBalance}),n=av(e=>e.errors.loadError,e=>()=>e),r=av(e=>e.errors.updateError,e=>()=>e),o=av(e=>e.statuses.isExecutingSpamCheck,e=>()=>!0===e),a=av(e=>e.statuses.isLoading,e=>()=>!0===e),s=av(e=>e.statuses.isUpdating,e=>()=>!0===e);return Oe((d=jS,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:i(d,{billingAddress:c,cart:l,consignments:u,coupons:h,customer:p,giftCertificates:m}),getLoadError:n(d),getUpdateError:r(d),isExecutingSpamCheck:o(d),isLoading:a(d),isUpdating:s(d)}))}(),b=function(){const e=av(e=>e.data,(e,{billingAddress:t})=>t.getOrderBillingAddress(),(e,{coupons:t})=>t.getCoupons(),(e,t,i=[])=>()=>{if(e&&t)return Object.assign(Object.assign({},e),{billingAddress:t,coupons:i})}),t=av(e,e=>()=>HS(e(),()=>new Xe(We.MissingOrder))),i=av(e=>e.meta,e=>()=>e),n=av(e=>e.errors.loadError,e=>()=>e),r=av(e=>{var t;return null===(t=e.data)||void 0===t?void 0:t.payments},(e=[])=>t=>{const i=e.find(({providerId:e})=>e===t);return null==i?void 0:i.paymentId}),o=av(e=>!!e.statuses.isLoading,e=>()=>e);return Oe((a=Pf,s,d)=>({getOrder:e(a,{billingAddress:s,coupons:d}),getOrderOrThrow:t(a,{billingAddress:s,coupons:d}),getOrderMeta:i(a),getLoadError:n(a),getPaymentId:r(a),isLoading:o(a)}))}(),P=function(){const e=av(e=>e.data,e=>()=>e);return Oe((t=Df)=>({getOrderBillingAddress:e(t)}))}(),O=function(){const e=av(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.payment}),t=av(({order:e})=>e.getOrder,e=>()=>{const t=e();return S(t&&t.payments,({providerId:e})=>"giftcertificate"!==e&&"storecredit"!==e)}),i=av(({checkout:e})=>e.getCheckout,e=>()=>{const t=e();return S(t&&t.payments,({providerType:e})=>"PAYMENT_TYPE_HOSTED"===e)}),n=av(e,i,t,(e,t,i)=>()=>{const n=e();if(n&&n.id)return{providerId:n.id,gatewayId:n.gateway};const r=t()||i();return r&&r.providerId?{providerId:r.providerId,gatewayId:r.gatewayId}:void 0}),r=av(n,e=>()=>HS(e(),()=>new Xe(We.MissingPaymentId))),o=av(e,i,t,(e,t,i)=>()=>{const n=e();if(n&&n.status)return n.status.replace("PAYMENT_STATUS_","");const r=t()||i();return r?r.detail.step:void 0}),a=av(o,e=>()=>HS(e(),()=>new Xe(We.MissingPaymentStatus))),s=av(({order:e})=>e.getOrderMeta,e=>()=>{const t=e();return t&&t.token}),d=av(s,e=>()=>HS(e(),()=>new Xe(We.MissingPaymentToken))),c=av(e,e=>()=>{const t=e();return t&&t.redirectUrl}),l=av(c,e=>()=>HS(e(),()=>new Xe(We.MissingPaymentRedirectUrl))),u=av(({checkout:e})=>e.getOutstandingBalance,e=>(t=!1)=>{const i=e(t);return!!i&&i>0}),h=av(o,e=>t=>!(!t||!t.nonce)||"ACKNOWLEDGE"===e()||e()===Ny);return Oe((e,t)=>({getPaymentId:n({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})}))}(),E=function(){const e=av(e=>e.errors.applyError,e=>()=>e),t=av(e=>!!e.statuses.isApplying,e=>()=>e);return Oe((i=KS)=>({getApplyError:e(i),isApplying:t(i)}))}(),k=function(){const e=av(e=>e.errors.updateError,e=>()=>e),t=av(e=>!!e.statuses.isUpdating,e=>()=>e);return Oe((i=FS)=>({getUpdateError:e(i),isUpdating:t(i)}))}(),D=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.errors.sendError,e=>()=>e),i=av(e=>!!e.statuses.isSending,e=>()=>e);return Oe((n=ES)=>({getEmail:e(n),getSendError:t(n),isSending:i(n)}))}(),M=function(){const e=av(e=>e.data,e=>()=>e),t=av(e=>e.data,e=>t=>null==e?void 0:e.find(e=>e.region===t)),i=av(e=>e.errors.loadError,e=>()=>e),n=av(e=>e.statuses.isLoading,e=>()=>!!e);return Oe((r=lf)=>({getExtensions:e(r),getExtensionByRegion:t(r),getLoadError:i(r),isLoading:n(r)}))}();return(f,S={})=>{const I=e(f.billingAddress),A=t(f.cart),T=i(f.checkoutButton),z=r(f.countries),N=o(f.coupons),x=a(f.customer),F=s(f.customerStrategies),R=M(f.extensions),L=l(f.formFields),B=d(f.giftCertificates),j=c(f.instruments),U=P(f.orderBillingAddress),q=u(f.paymentMethods),V=m(f.paymentProviderCustomer),G=h(f.paymentStrategies),H=p(f.pickupOptions),$=y(f.remoteCheckout),W=g(f.consignments),Y=v(f.shippingCountries),K=w(f.shippingStrategies),J=k(f.subscriptions),Z=E(f.storeCredit),X=D(f.signInEmail),Q=_(f.consignments,A),ee=C(f.checkout,I,A,Q,N,x,B),te=b(f.order,U,N),ie=O(ee,te),ne={billingAddress:I,cart:A,checkout:ee,checkoutButton:T,config:n(f.config,f.formFields),consignments:Q,countries:z,coupons:N,customer:x,customerStrategies:F,extensions:R,form:L,giftCertificates:B,instruments:j,order:te,orderBillingAddress:U,payment:ie,paymentMethods:q,paymentProviderCustomer:V,paymentStrategies:G,pickupOptions:H,remoteCheckout:$,shippingAddress:W,shippingCountries:Y,shippingStrategies:K,signInEmail:X,subscriptions:J,storeCredit:Z};return S.shouldWarnMutation?function(e){return Object.keys(e).reduce((t,i)=>(t[i]=$S(e[i]),t),{})}(ne):ne}}function ZS(e={},t){const i=(o=function(){const e=new uv;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 dv(e,t))}),e.register("invalid_payment_provider",e=>new Jr(e)),e.register("payment_config_not_found",e=>new Jr(e)),e}(),e=>le(e).pipe(ge(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}))),n=JS(),r=d({billingAddress:fv,cart:Pv,checkout:US,checkoutButton:Nv,config:Bv,consignments:aS,countries:If,coupons:Gv,customer:ef,customerStrategies:af,extensions:uf,formFields:gf,giftCertificates:Kv,instruments:Zf,orderBillingAddress:Mf,order:Of,payment:Nf,paymentMethods:Rf,paymentStrategies:Vf,pickupOptions:pS,paymentProviderCustomer:Yf,remoteCheckout:nS,shippingCountries:fS,shippingStrategies:CS,signInEmail:AS,subscriptions:RS,storeCredit:zS});var o;return u(r,e,Object.assign({actionTransformer:i,stateTransformer:e=>n(e)},t))}function XS(e){"https:"!==document.location.protocol&>().warn("The BigCommerce Checkout SDK should not be used on a non-HTTPS page"),"production"!==ht()&>().warn("Note that the development build is not optimized. To create a production build, set process.env.NODE_ENV to `production`.");const t={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:n="",shouldWarnMutation:r=!0,errorLogger:s=new lt}=e||{},d=i({host:e&&e.host}),c=ZS({config:t},{shouldWarnMutation:r}),l=Dm(c),u=new Em(d),h=new Qt(d),p=new St(new bt(d)),m=vi(o()),y=new fi(d),g=new ui(m,y),v=new km(u,new Vm(h)),f=new Cg(new bg(d)),S=new ni(new ri(d)),w=new ti(h,p,S),I=Ng(c),_=function(e,t,i={useFallback:!1}){const{useFallback:n}=i,r=new jt(n);for(const[,i]of Object.entries(t))if(Ft(i))for(const t of i.resolveIds){const n=Rt(()=>i(e),i.resolveIds);r.register(t,n)}return r}(I,$e,{useFallback:!0}),C=function(e,t){const i=new jt;for(const[,n]of Object.entries(t))if(Ft(n))for(const t of n.resolveIds){const r=Rt(()=>n(e),n.resolveIds);i.register(t,r)}return i}(I,He),b=new zi(new Ni(d)),P=new Vi,O=new Wi(c,P),E=ct(c,function(){const e=function(){const e=av(({checkout:e})=>e.getCheckout,e=>Ag(e)),t=av(({order:e})=>e.getOrder,e=>Ag(e)),i=av(({config:e})=>e.getStoreConfig,e=>Ag(e)),n=av(({shippingAddress:e})=>e.getShippingAddress,({config:e})=>e.getContextConfig,(e,t)=>Ag(()=>{const i=e(),n=t();if(!i){if(!n||!n.geoCountryCode)return;return{firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:n.geoCountryCode}}return i})),r=av(({consignments:e})=>e.getConsignments,e=>Ag(()=>{const t=e(),i=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==i?void 0:i.availableShippingOptions})),o=av(({consignments:e})=>e.getConsignments,e=>Ag(e)),a=av(({consignments:e})=>e.getConsignments,e=>Ag(()=>{const t=e(),i=null==t?void 0:t.find(e=>!e.selectedPickupOption);return null==i?void 0:i.selectedShippingOption})),s=av(({shippingCountries:e})=>e.getShippingCountries,e=>Ag(e)),d=av(({billingAddress:e})=>e.getBillingAddress,({config:e})=>e.getContextConfig,(e,t)=>Ag(()=>{const i=e(),n=t();return(!i||ne(G(i,"shouldSaveAddress","email","id")).every(e=>!e||!e.length))&&n&&n.geoCountryCode?{id:i?i.id:"",firstName:"",lastName:"",company:"",address1:"",address2:"",city:"",email:i?i.email:"",stateOrProvince:"",stateOrProvinceCode:"",postalCode:"",country:"",phone:"",customFields:[],countryCode:n.geoCountryCode}:i})),c=av(({countries:e})=>e.getCountries,e=>Ag(e)),l=av(({paymentMethods:e})=>e.getPaymentMethods,e=>Ag(e)),u=av(({paymentMethods:e})=>e.getPaymentMethod,e=>Ag(e)),h=av(({payment:e})=>e.getPaymentId,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Ag(()=>{const i=e();return i&&t(i.providerId,i.gatewayId)})),p=av(({cart:e})=>e.getCart,e=>Ag(e)),m=av(({coupons:e})=>e.getCoupons,e=>Ag(e)),y=av(({giftCertificates:e})=>e.getGiftCertificates,e=>Ag(e)),g=av(({customer:e})=>e.getCustomer,e=>Ag(e)),v=av(({signInEmail:e})=>e.getEmail,e=>Ag(e)),f=av(({payment:e})=>e.isPaymentDataRequired,e=>Ag(e)),S=av(({payment:e})=>e.isPaymentDataSubmitted,({paymentMethods:e})=>e.getPaymentMethod,(e,t)=>Ag((i,n)=>e(t(i,n)))),w=av(({instruments:e})=>e.getInstruments,({instruments:e})=>e.getInstrumentsByPaymentMethod,(e,t)=>Ag(function(i){return i?t(i):e()})),I=av(({form:e})=>e.getCustomerAccountFields,e=>Ag(e)),_=av(({form:e})=>e.getBillingAddressFields,({countries:e})=>e.getCountries,(e,t)=>Ag(i=>e(t(),i))),C=av(({form:e})=>e.getShippingAddressFields,({shippingCountries:e})=>e.getShippingCountries,(e,t)=>Ag(i=>e(t(),i))),b=av(({config:e})=>e.getFlashMessages,e=>Ag(e)),P=av(({pickupOptions:e})=>e.getPickupOptions,e=>Ag(e)),O=av(({config:e})=>e.getStoreConfig,e=>Ag(()=>{const t=e();if(t)return t.checkoutSettings.checkoutUserExperienceSettings})),E=av(({extensions:e})=>e.getExtensions,e=>Ag(e)),A=av(({paymentProviderCustomer:e})=>e.getPaymentProviderCustomer,e=>Ag(e)),T=av(({extensions:e})=>e.getExtensionByRegion,e=>Ag(e));return Oe(k=>({getCheckout:e(k),getOrder:t(k),getConfig:i(k),getExtensions:E(k),getExtensionByRegion:T(k),getFlashMessages:b(k),getShippingAddress:n(k),getShippingOptions:r(k),getConsignments:o(k),getSelectedShippingOption:a(k),getShippingCountries:s(k),getBillingAddress:d(k),getBillingCountries:c(k),getPaymentMethods:l(k),getPaymentMethod:u(k),getSelectedPaymentMethod:h(k),getCart:p(k),getCoupons:m(k),getGiftCertificates:y(k),getCustomer:g(k),isPaymentDataRequired:f(k),isPaymentDataSubmitted:S(k),getSignInEmail:v(k),getInstruments:w(k),getCustomerAccountFields:I(k),getBillingAddressFields:_(k),getShippingAddressFields:C(k),getPickupOptions:P(k),getUserExperienceSettings:O(k),getPaymentProviderCustomer:A(k)}))}(),t=function(){const e=sv(e=>e,e=>()=>{for(const t of Object.keys(e)){const i=e[t]();if(i)return i}}),t=av(({shippingStrategies:e})=>e.getSelectOptionError,({consignments:e})=>e.getUpdateShippingOptionError,(e,t)=>i=>e()||t(i));return Oe(i=>{const n={getLoadCheckoutError:i.checkout.getLoadError,getUpdateCheckoutError:i.checkout.getUpdateError,getSubmitOrderError:i.paymentStrategies.getExecuteError,getFinalizeOrderError:i.paymentStrategies.getFinalizeError,getLoadOrderError:i.order.getLoadError,getLoadCartError:i.cart.getLoadError,getLoadBillingCountriesError:i.countries.getLoadError,getLoadShippingCountriesError:i.shippingCountries.getLoadError,getLoadPaymentMethodsError:i.paymentMethods.getLoadError,getLoadPaymentMethodError:i.paymentMethods.getLoadMethodError,getInitializePaymentError:i.paymentStrategies.getInitializeError,getSignInError:i.customerStrategies.getSignInError,getSignOutError:i.customerStrategies.getSignOutError,getInitializeCustomerError:i.customerStrategies.getInitializeError,getLoadShippingOptionsError:i.consignments.getLoadShippingOptionsError,getSelectShippingOptionError:t(i),getContinueAsGuestError:i.billingAddress.getContinueAsGuestError,getUpdateBillingAddressError:i.billingAddress.getUpdateError,getUpdateSubscriptionsError:i.subscriptions.getUpdateError,getUpdateShippingAddressError:i.shippingStrategies.getUpdateAddressError,getDeleteConsignmentError:i.consignments.getDeleteError,getUpdateConsignmentError:i.consignments.getUpdateError,getCreateConsignmentsError:i.consignments.getCreateError,getInitializeShippingError:i.shippingStrategies.getInitializeError,getApplyStoreCreditError:i.storeCredit.getApplyError,getApplyCouponError:i.coupons.getApplyError,getRemoveCouponError:i.coupons.getRemoveError,getApplyGiftCertificateError:i.giftCertificates.getApplyError,getRemoveGiftCertificateError:i.giftCertificates.getRemoveError,getLoadInstrumentsError:i.instruments.getLoadError,getDeleteInstrumentError:i.instruments.getDeleteError,getLoadConfigError:i.config.getLoadError,getSignInEmailError:i.signInEmail.getSendError,getCreateCustomerAccountError:i.customer.getCreateAccountError,getCreateCustomerAddressError:i.customer.getCreateAddressError,getPickupOptionsError:i.pickupOptions.getLoadError,getLoadExtensionsError:i.extensions.getLoadError};return Object.assign({getError:e(n)},n)})}(),i=function(){const e=sv(e=>e,e=>()=>Object.keys(e).some(t=>e[t]())),t=av(({shippingStrategies:e})=>e.isSelectingOption,({consignments:e})=>e.isUpdatingShippingOption,(e,t)=>i=>e()||t(i)),i=av(({customerStrategies:e})=>e.isInitializing,({customerStrategies:e})=>e.isSigningIn,({customerStrategies:e})=>e.isSigningOut,({customerStrategies:e})=>e.isExecutingPaymentMethodCheckout,({customerStrategies:e})=>e.isWidgetInteracting,(e,t,i,n,r)=>o=>e(o)||t(o)||i(o)||n(o)||r(o)),n=av(({shippingStrategies:e})=>e.isInitializing,({shippingStrategies:e})=>e.isUpdatingAddress,({shippingStrategies:e})=>e.isSelectingOption,({shippingStrategies:e})=>e.isWidgetInteracting,(e,t,i,n)=>r=>e(r)||t(r)||i(r)||n(r)),r=av(({paymentStrategies:e})=>e.isInitializing,({paymentStrategies:e})=>e.isExecuting,({paymentStrategies:e})=>e.isFinalizing,({paymentStrategies:e})=>e.isWidgetInteracting,(e,t,i,n)=>r=>e(r)||t(r)||i(r)||n(r)),o=av(({paymentStrategies:e})=>e.isExecuting,({checkout:e})=>e.isExecutingSpamCheck,(e,t)=>i=>e(i)||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,isCustomerStepPending:i(a),isShippingStepPending:n(a),isPaymentStepPending:r(a),isLoadingPickupOptions:a.pickupOptions.isLoading};return Object.assign({isPending:e(s)},s)})}();return n=>({data:e(n),errors:t(n),statuses:i(n)})}());return new rv(c,E,O,function(e,t){const i={[Hi.ConsignmentsChanged]:Ki};return new Yi(e,t,i)}(E,O),new tt(new at(d),f),w,p,new Ht(new $t(d),w,g),new hg(new mg(d),h),new Im(new _m(d,{locale:n})),new Ot(new zt(d)),new Zt(function(e,t){const i=new Bt,n=a(),r=new Qt(t),o=new ti(r,new St(new bt(t)),new ni(new ri(t))),s=new ui(vi(n),new fi(t)),d=new Ht(new $t(t),o,s);return i.register("default",()=>new Si(e,d)),i}(c,d),C,I,s),new ut,new Nt(new xt(d)),new xg(new jg(l,d)),v,new zm(new Nm(d)),new jm(function(e,t,i){const n=new zy({defaultToken:Lm.CREDIT_CARD}),r=a(),s=new Dy,d=new uy(t),c=new Qt(i),l=new Vm(c),u=new km(new Em(i),l),h=new Jm(vi(o())),p=new ly(d,u,s,h),m=Ee(),y=((e,t)=>new Gy(new Vy(e,t)))(m,h),g=new cy(e);return n.register(Lm.CONVERGE,()=>new Ly(e,u,p,g,m)),n.register(Lm.PPSDK,()=>new Ky(e,u,((e,t,i,n,r)=>{const o=new Zy;return o.register(Wy.CARD,()=>new Qy(e,t,r,n)),o.register(Wy.NONE,()=>new eg(i,n)),o.register(Wy.UNSUPPORTED,()=>{}),o})(e,u,i,y,g),new rg(i,y),new Gm("PPSDK"))),n.register(Lm.WE_PAY,()=>new og(e,u,p,g,new ag(r))),n}(c,l,d),_,v,g,I,s),new Ug(new qg(d)),new vg(new fg(d,{locale:n}),c),new Vg(function(e,t){const i=new Bt,n=Ng(e),r=new Qt(t),o=new mg(t),s=new hg(o,r),d=new zm(new Nm(t)),c=a(),l=new Cg(new bg(t)),u=new tt(new at(t),l),h=window,p=new bn(n);return i.register("amazonpay",()=>new $g(e,s,new zm(new Nm(t)),yn(),new Vg(i))),i.register("stripeupe",()=>new Qg(e,new ka(c),s,d)),i.register("braintreeacceleratedcheckout",()=>new Yg(e,u,s,d,new dg,new vo(new qn(a(),h,p),h))),i.register("paypalcommerceacceleratedcheckout",()=>new Zg(e,u,s,d,new dg,Rs(),js())),i.register("default",()=>new Kg(e,s)),i}(c,d)),new ev(new tv(d)),g,new wg(new Ig(d)),f,S,b,P)}class QS extends Ji{constructor(e){super(e||"An unexpected error has occurred during config creation process. Please try again later."),this.name="AmazonPayV2ConfigCreationError",this.type="amazon_pay_v2_config_creation_error"}}function ew(e){return e instanceof Object&&"buyNowInitializeOptions"in e}var tw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class iw{constructor(e,t,i){this.paymentIntegrationService=e,this.amazonPayV2PaymentProcessor=t,this.amazonPayV2ConfigRequestSender=i}initialize(e){var t;return tw(this,void 0,void 0,function*(){const{methodId:i,containerId:n,amazonpay:r}=e,{buttonColor:o}=r||{};if(!i||!n)throw new gn('Unable to proceed because "methodId" or "containerId" argument is not provided.');const{getPaymentMethodOrThrow:a}=this.paymentIntegrationService.getState(),s=a(i),{initializationData:d}=s;yield this.amazonPayV2PaymentProcessor.initialize(s),r||(yield this.paymentIntegrationService.loadDefaultCheckout());const c=ew(r)?void 0:r;ew(r)&&"function"==typeof(null===(t=r.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)&&(this._buyNowInitializeOptions=r.buyNowInitializeOptions,this.amazonPayV2PaymentProcessor.updateBuyNowFlowFlag(!0)),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:n,methodId:i,options:c,placement:an.Cart,buttonColor:o,isButtonMicroTextDisabled:null==d?void 0:d.isButtonMicroTextDisabled}),this._buyNowInitializeOptions&&this.amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(this._getCheckoutCreationRequestConfig.bind(this))})}deinitialize(){return this.amazonPayV2PaymentProcessor.deinitialize()}_createBuyNowCartOrThrow(){var e,t;return tw(this,void 0,void 0,function*(){const i=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!i)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(i)}catch(e){throw new Zn}})}_createCheckoutConfig(e){return tw(this,void 0,void 0,function*(){try{const t=(yield this.amazonPayV2ConfigRequestSender.createCheckoutConfig(e)).body,{payload:i,public_key:n}=t,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(t,["payload","public_key"]);return Object.assign({payloadJSON:i,publicKeyId:n},r)}catch(e){throw new QS}})}_getCheckoutCreationRequestConfig(){return tw(this,void 0,void 0,function*(){const e=yield this._createBuyNowCartOrThrow(),t={amount:String(e.baseAmount),currencyCode:e.currency.code};return{createCheckoutSessionConfig:yield this._createCheckoutConfig(e.id),estimatedOrderAmount:t,productType:0===en(e)?dn.PayOnly:dn.PayAndShip}})}}class nw{constructor(e){this._requestSender=e}createCheckoutConfig(e){const t={cartId:e},i=Object.assign({"X-API-INTERNAL":cr,"Content-Type":ur.Json},hr);return this._requestSender.post("/api/storefront/payment/amazonpay",{headers:i,body:t})}}const rw=Rt(e=>{const t=i(),n=new nw(t),r=yn();return new iw(e,r,n)},[{id:"amazonpay"}]);var ow,aw,sw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(ow||(ow={})),function(e){e.Black="black",e.White="white",e.WhiteBorder="white-border"}(aw||(aw={}));class dw{constructor(e,t,i,n,r){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=i,this._braintreeSdk=n,this._applePayScriptLoader=r,this._onAuthorizeCallback=V,this._subTotalLabel=ow.Subtotal,this._shippingLabel=ow.Shipping}initialize(e){var t,i;return sw(this,void 0,void 0,function*(){const{methodId:n,containerId:r,applepay:o}=e;if(!n||!o)throw new Qi(Zi.MissingPaymentMethod);yield this._applePayScriptLoader.loadSdk();const{onPaymentAuthorize:a,buyNowInitializeOptions:s,requiresShipping:d}=o;this._requiresShipping=d,this._buyNowInitializeOptions=s,this._onAuthorizeCallback=a,s||(yield this._paymentIntegrationService.loadDefaultCheckout()),yield this._paymentIntegrationService.loadPaymentMethod(n);const c=this._paymentIntegrationService.getState();return this._paymentMethod=c.getPaymentMethodOrThrow(n),c.getCart()&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection()),(null===(t=this._paymentMethod.initializationData)||void 0===t?void 0:t.gateway)===jn.BRAINTREE&&this._paymentMethod.clientToken&&this._braintreeSdk.initialize(this._paymentMethod.clientToken),this._applePayButton=this._createButton(r,null===(i=this._paymentMethod.initializationData)||void 0===i?void 0:i.styleOption),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),Promise.resolve()})}deinitialize(){return Promise.resolve()}_createButton(e,t){const i=document.getElementById(e);if(!i)throw new gn("Unable to create wallet button without valid container ID.");const n=this._createApplePayButtonElement(t);return i.appendChild(n),n}_createApplePayButtonElement(e){const t=document.createElement("apple-pay-button");return t.setAttribute("buttonstyle",(e=>{switch(e){case aw.White:return"white";case aw.WhiteBorder:return"white-outline";case aw.Black:default:return"black"}})(e)),t.setAttribute("type","plain"),t.setAttribute("style","--apple-pay-button-width: 100%; --apple-pay-button-height: 40px; --apple-pay-button-border-radius: 4px;"),t}_handleWalletButtonClick(e){var t;return sw(this,void 0,void 0,function*(){if(e.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new Qi(Zi.MissingPaymentMethod);if(this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody){const{countryCode:e,currencyCode:i,merchantCapabilities:n,supportedNetworks:r,storeName:o}=this._paymentMethod.initializationData,a=this._getRequestWithEmptyTotal(e,i,r,n);this._requiresShipping&&(null===(t=a.requiredShippingContactFields)||void 0===t||t.push("postalAddress"));const s=this._sessionFactory.create(a);this._handleApplePayEvents(s,this._paymentMethod,o),s.begin()}else{const e=this._paymentIntegrationService.getState(),t=e.getCartOrThrow(),i=e.getStoreConfigOrThrow(),n=e.getCheckoutOrThrow(),r=this._getBaseRequest(t,n,i,this._paymentMethod),o=this._sessionFactory.create(r);this._handleApplePayEvents(o,this._paymentMethod,i.storeProfile.storeName),o.begin()}})}_getRequestWithEmptyTotal(e,t,i,n){return{countryCode:e,currencyCode:t,supportedNetworks:i,merchantCapabilities:n,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}}_getBaseRequest(e,t,i,n){var r;const{storeProfile:{storeCountryCode:o,storeName:a}}=i,{currency:{code:s,decimalPlaces:d}}=e,{initializationData:{merchantCapabilities:c,supportedNetworks:l}}=n,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,i){e.onvalidatemerchant=i=>sw(this,void 0,void 0,function*(){try{const{body:n}=yield this._onValidateMerchant(t,i);e.completeMerchantValidation(n)}catch(e){throw new Error("Merchant validation failed")}}),this._buyNowInitializeOptions&&!this._requiresShipping&&(e.onpaymentmethodselected=()=>sw(this,void 0,void 0,function*(){yield this._createBuyNowCart(),this._handlePaymentMethodSelected(e)})),e.onshippingcontactselected=t=>sw(this,void 0,void 0,function*(){this._buyNowInitializeOptions&&this._requiresShipping&&(yield this._createBuyNowCart()),yield this._handleShippingContactSelected(e,i,t)}),e.onshippingmethodselected=t=>sw(this,void 0,void 0,function*(){yield this._handleShippingMethodSelected(e,i,t)}),e.oncancel=()=>sw(this,void 0,void 0,function*(){try{const e=`/remote-checkout/${t.id}/signout`;return yield this._requestSender.get(e),yield this._paymentIntegrationService.loadCheckout()}catch(e){throw new Vn}}),e.onpaymentauthorized=i=>sw(this,void 0,void 0,function*(){return this._onPaymentAuthorized(i,e,t)})}_createBuyNowCart(){var e,t;return sw(this,void 0,void 0,function*(){try{const i=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e);if(!i)throw new Qi(Zi.MissingCart);const n=yield this._paymentIntegrationService.createBuyNowCart(i);yield this._paymentIntegrationService.loadCheckout(n.id);const r=this._paymentIntegrationService.getState(),{shouldExecuteSpamCheck:o}=r.getCheckoutOrThrow();o&&(yield this._paymentIntegrationService.verifyCheckoutSpamProtection())}catch(e){throw new Zn}})}_handlePaymentMethodSelected(e){const t=this._paymentIntegrationService.getState(),i=t.getCartOrThrow(),n=t.getStoreConfigOrThrow(),r=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new Qi(Zi.MissingPaymentMethod);const o=this._getBaseRequest(i,r,n,this._paymentMethod);delete o.total.type,e.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})}_handleShippingContactSelected(e,t,i){var n;return sw(this,void 0,void 0,function*(){const r=this._transformContactToAddress(i.shippingContact);try{yield this._paymentIntegrationService.updateShippingAddress(r)}catch(t){throw e.abort(),new Error("Shipping address update failed")}let o=this._paymentIntegrationService.getState();const{currency:{decimalPlaces:a}}=o.getCartOrThrow();let s=o.getCheckoutOrThrow();const d=null===(n=s.consignments[0].selectedShippingOption)||void 0===n?void 0:n.id,c=s.consignments[0].availableShippingOptions,l=null==c?void 0:c.find(({id:e})=>e===d),u=null==c?void 0:c.filter(e=>e.id!==d),h=l?[{label:l.description,amount:`${l.cost.toFixed(a)}`,detail:l.additionalDescription,identifier:l.id}]:[];if(u&&[...u.filter(e=>e.isRecommended),...u.filter(e=>!e.isRecommended)].forEach(e=>h.push({label:e.description,amount:`${e.cost.toFixed(a)}`,detail:e.additionalDescription,identifier:e.id})),!(c instanceof Array))throw new Error("Shipping options not available.");if(0===c.length)return void e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:t,amount:`${s.grandTotal.toFixed(a)}`},[]);const p=c.find(e=>e.isRecommended),m=p?p.id:c[0].id,y=l?l.id:m;try{yield this._updateShippingOption(y)}catch(e){throw new Error("Shipping options update failed")}o=this._paymentIntegrationService.getState(),s=o.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:h,newTotal:{type:"final",label:t,amount:`${s.grandTotal.toFixed(a)}`},newLineItems:this._getUpdatedLineItems(s,a)})})}_handleShippingMethodSelected(e,t,i){return sw(this,void 0,void 0,function*(){const{shippingMethod:{identifier:n}}=i;try{yield this._updateShippingOption(n)}catch(t){throw e.abort(),new Error("Shipping option selection update failed.")}const r=this._paymentIntegrationService.getState(),{currency:{decimalPlaces:o}}=r.getCartOrThrow(),a=r.getCheckoutOrThrow();e.completeShippingMethodSelection({newTotal:{type:"final",label:t,amount:`${a.grandTotal.toFixed(o)}`},newLineItems:this._getUpdatedLineItems(a,o)})})}_getUpdatedLineItems(e,t){const i=[{label:this._subTotalLabel,amount:`${e.subtotal.toFixed(t)}`}];return e.taxes.forEach(e=>i.push({label:e.name,amount:`${e.amount.toFixed(t)}`})),i.push({label:this._shippingLabel,amount:`${e.shippingCostTotal.toFixed(t)}`}),i}_updateShippingOption(e){return sw(this,void 0,void 0,function*(){return this._paymentIntegrationService.selectShippingOption(e)})}_onValidateMerchant(e,t){return sw(this,void 0,void 0,function*(){const i=[`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:i})})}_onPaymentAuthorized(e,t,i){var n;return sw(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===(n=i.initializationData)||void 0===n?void 0:n.gateway)===jn.BRAINTREE&&(d=yield this._getBraintreeDeviceData());const c={methodId:i.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){throw t.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete")}})}_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 sw(this,void 0,void 0,function*(){try{const{deviceData:e}=yield this._braintreeSdk.getDataCollectorOrThrow();return e}catch(e){}})}}const cw=Rt(e=>{const{getHost:t}=e.getState(),n=new bn(e);return new dw(i({host:t()}),e,new Yn,new Ln(new qn(a(),window,n)),new Kn(new r))},[{id:"applepay"}]);var lw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class uw{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){var t;return lw(this,void 0,void 0,function*(){const{bigcommerce_payments:i,containerId:n,methodId:r}=e,o=Boolean(null==i?void 0:i.buyNowInitializeOptions);if(!r)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.bigcommerce_payments" argument is not provided.');if(o&&!i.currencyCode)throw new gn('Unable to initialize payment because "options.bigcommerce_payments.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=i.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.bigcommerce_payments.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?i.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(n,r,i,o)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i,n){var r,o;const{buyNowInitializeOptions:a,style:s,onComplete:d,onEligibilityFailure:c}=i,l=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),u=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:h,isAppSwitchEnabled:p}=u.initializationData||{},m=Object.assign(Object.assign({},!n&&this.isPaypalCommerceAppSwitchEnabled(t)&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)}),y={onClick:()=>this.handleClick(a),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},g=Object.assign(Object.assign({},!p&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,d)}),v=Object.assign(Object.assign(Object.assign({fundingSource:l.FUNDING.PAYPAL,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(s)},m),a&&y),h&&g),f=l.Buttons(v);f.isEligible()?(null===(r=f.hasReturned)||void 0===r?void 0:r.call(f))&&this.isPaypalCommerceAppSwitchEnabled(t)?null===(o=f.resume)||void 0===o||o.call(f):f.render(`#${e}`):c&&"function"==typeof c?c():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return lw(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return lw(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return lw(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){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return lw(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){if("string"==typeof e)throw new Error(e);throw e}})}isPaypalCommerceAppSwitchEnabled(e){var t,i;return null!==(i=null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)&&void 0!==i&&i}}const hw=Rt(e=>new uw(e,vr(e)),[{id:"bigcommerce_payments"}]);var pw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class mw{constructor(e,t,i){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t,this.payPalSdkHelper=i}initialize(e){return pw(this,void 0,void 0,function*(){const{bigcommerce_payments_paylater:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:r,currencyCode:o,messagingContainerId:a}=t||{},s=!!r;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater" argument is not provided.');if(s&&!o)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.bigcommerce_payments_paylater.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');s||(yield this.paymentIntegrationService.loadDefaultCheckout());const d=this.paymentIntegrationService.getState(),c=s?o:d.getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,c,!1),this.renderButton(i,n,t);const l=a&&document.getElementById(a);if(c&&l){const e=d.getPaymentMethodOrThrow(n),{paypalBNPLConfiguration:t=[]}=e.initializationData||{},i=t&&t.find(({id:e})=>"cart"===e);if(!(null==i?void 0:i.status))return;l.removeAttribute("data-pp-style-logo-type"),l.removeAttribute("data-pp-style-logo-position"),l.removeAttribute("data-pp-style-text-color"),l.removeAttribute("data-pp-style-text-size");const r=yield this.payPalSdkHelper.getPayPalMessages(e,c);this.renderMessages(r,a,i)}})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:r,onComplete:o,onEligibilityFailure:a}=i,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c}=d.initializationData||{},l={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_paylater"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},u={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},h={onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e),onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,o)},p=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let m=!1;p.forEach(t=>{if(!m){const i=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(r)},l),n&&u),c&&h),o=s.Buttons(i);o.isEligible()?(o.render(`#${e}`),m=!0):a&&"function"==typeof a&&a()}}),m||this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return pw(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return pw(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.bigCommercePaymentsIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return pw(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){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return pw(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){if("string"==typeof e)throw new Error(e);throw e}})}renderMessages(e,t,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:$d(i)};e.Messages(n).render(`#${t}`)}}const yw=Rt(e=>new mw(e,vr(e),zr()),[{id:"bigcommerce_payments_paylater"}]);var gw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class vw{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return gw(this,void 0,void 0,function*(){const{bigcommerce_payments_apms:t,containerId:i,methodId:n}=e,{apm:r,buyNowInitializeOptions:o,currencyCode:a}=t||{},s=!!o;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_apms" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_apms.apm" argument is not provided.');if(s&&!a)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_apms.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.bigcommerce_payments_apms.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');s||(yield this.paymentIntegrationService.loadDefaultCheckout());const d=s?a:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,d,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{apm:n,buyNowInitializeOptions:r,style:o,onEligibilityFailure:a}=i,s=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow();if(!Object.values(s.FUNDING).includes(n))throw new gn('Unable to initialize PayPal button because "options.bigcommerce_payments_apms.apm" argument is not valid funding source.');const d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_apms"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(r),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:n,style:this.bigCommercePaymentsIntegrationService.getValidButtonStyle(o)},d),r&&c),u=s.Buttons(l);u.isEligible()?u.render(`#${e}`):a&&"function"==typeof a?a():this.bigCommercePaymentsIntegrationService.removeElement(e)}handleClick(e){return gw(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const fw=Rt(e=>new vw(e,vr(e)),[{id:"bigcommerce_payments_apms"}]);var Sw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class ww{constructor(e,t){this.paymentIntegrationService=e,this.bigCommercePaymentsIntegrationService=t}initialize(e){return Sw(this,void 0,void 0,function*(){const{bigcommerce_payments_venmo:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo" argument is not provided.');if(a&&!o)throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.bigcommerce_payments_venmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.bigCommercePaymentsIntegrationService.loadPayPalSdk(n,s,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:r,onEligibilityFailure:o}=i,a=this.bigCommercePaymentsIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.bigCommercePaymentsIntegrationService.createOrder("bigcommerce_payments_venmo"),onApprove:({orderID:e})=>this.bigCommercePaymentsIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),n&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.bigCommercePaymentsIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.bigCommercePaymentsIntegrationService.getValidButtonStyle(e);return t.color===nr.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return Sw(this,void 0,void 0,function*(){if(e){const t=yield this.bigCommercePaymentsIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const Iw=Rt(e=>new ww(e,vr(e)),[{id:"bigcommerce_payments_venmo"}]);class _w{constructor(e,t,i=window){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=i}initialize(e){return t=this,i=void 0,r=function*(){const{bolt:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:r,style:o}=t||{};if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(r))throw new vn("Only buy now flow is implemented for Bolt button");if(!(null==r?void 0:r.storefrontApiToken)||"string"!=typeof r.storefrontApiToken)throw new gn('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');const a=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{initializationData:s,config:d}=a,{publishableKey:c,developerConfig:l}=s||{};yield this.boltScriptLoader.loadBoltClient(c,d.testMode,l,"BigCommerce",r.storefrontApiToken),this.renderButton(i,a,o)},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}deinitialize(){return Promise.resolve()}renderButton(e,t,i){var n;"function"==typeof(null===(n=this.boltHostWindow.BoltConnect)||void 0===n?void 0:n.setupProductPageCheckout)&&(this.addButtonContainer(e,t,i),this.boltHostWindow.BoltConnect.setupProductPageCheckout())}addButtonContainer(e,t,i){const n=document.getElementById(e);if(!n)return;const r=document.createElement("div"),o=document.createElement("object");r.setAttribute("id","product-page-checkout-wrapper"),r.setAttribute("class","bolt-button-wrapper"),r.setAttribute("style","display:none"),r.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(t,i)),o.setAttribute("class","bolt-product-checkout-button"),r.append(o),n.innerHTML="",n.append(r)}getBoltObjectData(e,t){const{initializationData:i,config:n}=e,{publishableKey:r,developerConfig:o}=i||{},a=this.boltScriptLoader.getDomainURL(!!n.testMode,o),s=this.getButtonHeight(null==t?void 0:t.size),d=this.getButtonBorderRadius(null==t?void 0:t.shape,s);return xe({url:`https://${a}/v1/checkout_button`,query:{publishable_key:r,variant:"ppc",height:s,border_radius:d}})}getButtonHeight(e){if(e)switch(e){case Xr.Small:return 25;case Xr.Large:return 45;case Xr.Medium:default:return 40}}getButtonBorderRadius(e,t){if(e)switch(e){case Qr.Pill:return t?Math.round(t/2):void 0;case Qr.Rect:default:return 4}}}const Cw=Rt(e=>new _w(e,new no(a())),[{id:"bolt"}]);function bw(e){const{color:t,fundingicons:i,height:n=40,layout:r,shape:o,size:a,tagline:s}=e||{},d={color:t,fundingicons:i,height:Pw(n),layout:r,shape:o||"rect",size:a,tagline:s};return H(d,k)}function Pw(e){const t=Number(e);return!t||Number.isNaN(t)?40:t>55?55:t<25?25:t}var Ow=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class Ew{constructor(e,t,i,n){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeHostWindow=n}initialize(e){return Ow(this,void 0,void 0,function*(){const{braintreepaypal:t,containerId:i,methodId:n}=e;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');let r,o=this.paymentIntegrationService.getState();if(t.buyNowInitializeOptions){if(!t.currencyCode)throw new gn('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');r=t.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),o=this.paymentIntegrationService.getState(),r=o.getCartOrThrow().currency.code;const a=o.getPaymentMethodOrThrow(n),{clientToken:s,config:d,initializationData:c}=a;if(!s||!c)throw new Qi(Zi.MissingPaymentMethod);const l={currency:r,intent:c.intent,isCreditEnabled:c.isCreditEnabled,commit:!1};this.braintreeIntegrationService.initialize(s),yield this.braintreeIntegrationService.getPaypalCheckout(l,e=>{this.renderPayPalButton(e,t,i,n,!!d.testMode)},e=>this.handleError(e,i,t.onError))})}deinitialize(){return Ow(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalButton(e,t,i,n,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;if(c){const l=c.Buttons({env:r?"sandbox":"production",fundingSource:c.FUNDING.PAYPAL,style:bw(o),createOrder:()=>this.setupPayment(e,t,n),onApprove:t=>this.tokenizePayment(t,e,n,a,s)});l.isEligible()?l.render(`#${i}`):d&&"function"==typeof d&&d()}else this.braintreeIntegrationService.removeElement(i)}setupPayment(e,t,i){var n;return Ow(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(i),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?cl(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!1,intent:null===(n=c.initializationData)||void 0===n?void 0:n.intent})}catch(e){throw r&&(zn(e)||e instanceof Ji)&&r(e),e}})}tokenizePayment(e,t,i,n,r){return Ow(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:i,action:n?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(zn(e)||e instanceof Ji)&&r(e),e}})}createBuyNowCart(e){return Ow(this,void 0,void 0,function*(){if(!e)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new Zn}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!zn(e))throw e;i(e)}}const Aw=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t);return new Ew(e,Ee(),n,t)},[{id:"braintreepaypal"}]);var Tw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class kw{constructor(e,t,i,n,r){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=i,this.braintreeMessages=n,this.braintreeHostWindow=r}initialize(e){var t,i;return Tw(this,void 0,void 0,function*(){const{braintreepaypalcredit:n,containerId:r,methodId:o}=e;if(!o)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');let a,s=this.paymentIntegrationService.getState();if(n.buyNowInitializeOptions){if(!n.currencyCode)throw new gn('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');a=n.currencyCode}else yield this.paymentIntegrationService.loadDefaultCheckout(),s=this.paymentIntegrationService.getState(),a=s.getCartOrThrow().currency.code;const d=s.getPaymentMethodOrThrow(o),{clientToken:c,config:l,initializationData:u}=d;if(!c||!u)throw new Qi(Zi.MissingPaymentMethod);const h={currency:a,intent:u.intent,isCreditEnabled:u.isCreditEnabled,commit:!1},p=Wt(null!==(i=null===(t=s.getStoreConfig())||void 0===t?void 0:t.checkoutSettings.features)&&void 0!==i?i:{},"PAYPAL-5663.hide_braintree_card_banner_implementation_in_checkout_sdk");this.braintreeIntegrationService.initialize(c),yield this.braintreeIntegrationService.getPaypalCheckout(h,e=>{!p&&n.messagingContainerId&&this.renderPayPalMessages(o,n.messagingContainerId),this.renderPayPalButton(e,n,r,o,!!l.testMode)},e=>this.handleError(e,r,n.onError))})}deinitialize(){return Tw(this,void 0,void 0,function*(){yield this.braintreeIntegrationService.teardown()})}renderPayPalMessages(e,t){this.braintreeMessages.render(e,t,yo.CART)}renderPayPalButton(e,t,i,n,r){const{style:o,shouldProcessPayment:a,onAuthorizeError:s,onEligibilityFailure:d}=t,{paypal:c}=this.braintreeHostWindow;let l=!1;c&&[c.FUNDING.PAYLATER,c.FUNDING.CREDIT].forEach(u=>{const h=u===c.FUNDING.CREDIT?Object.assign({label:po.CREDIT},bw(o)):bw(o);if(!l){const o=c.Buttons({env:r?"sandbox":"production",fundingSource:u,style:h,createOrder:()=>this.setupPayment(e,t,n),onApprove:t=>this.tokenizePayment(t,e,n,a,s)});o.isEligible()?(o.render(`#${i}`),l=!0):c.FUNDING.CREDIT&&d&&"function"==typeof d&&d()}}),c&&l||this.braintreeIntegrationService.removeElement(i)}setupPayment(e,t,i){var n;return Tw(this,void 0,void 0,function*(){const{onPaymentError:r,shippingAddress:o,buyNowInitializeOptions:a}=t;try{const r="function"==typeof(null==a?void 0:a.getBuyNowCartRequestBody)?yield this.createBuyNowCart(a.getBuyNowCartRequestBody()):void 0;this.buyNowCartId=null==r?void 0:r.id;const s=this.paymentIntegrationService.getState(),d=s.getCustomer(),c=s.getPaymentMethodOrThrow(i),l=r?r.cartAmount:s.getCartOrThrow().cartAmount,u=r?t.currencyCode:s.getCartOrThrow().currency.code,h=o||(null==d?void 0:d.addresses[0]),p=h?cl(h):void 0;return yield e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:p,amount:l,currency:u,offerCredit:!0,intent:null===(n=c.initializationData)||void 0===n?void 0:n.intent})}catch(e){throw r&&(zn(e)||e instanceof Ji)&&r(e),e}})}tokenizePayment(e,t,i,n,r){return Tw(this,void 0,void 0,function*(){try{const{deviceData:r}=yield this.braintreeIntegrationService.getDataCollector({paypal:!0}),o=yield t.tokenizePayment(e),{details:a,nonce:s}=o,d=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),c=this.braintreeIntegrationService.mapToLegacyShippingAddress(a);return this.formPoster.postForm("/checkout.php",Object.assign({payment_type:"paypal",provider:i,action:n?"process_payment":"set_external_checkout",nonce:s,device_data:r,billing_address:JSON.stringify(d),shipping_address:JSON.stringify(c)},this.buyNowCartId&&{cart_id:this.buyNowCartId})),o}catch(e){throw r&&(zn(e)||e instanceof Ji)&&r(e),e}})}createBuyNowCart(e){return Tw(this,void 0,void 0,function*(){if(!e)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(e)}catch(e){throw new Zn}})}handleError(e,t,i){if(this.braintreeIntegrationService.removeElement(t),!i||!zn(e))throw e;i(e)}}const Dw=Rt(e=>{const t=window,i=new bn(e),n=new vo(new qn(a(),t,i),t),r=new ol(e);return new kw(e,Ee(),n,r,t)},[{id:"braintreepaypalcredit"}]);var Mw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class zw{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i}initialize(e){return Mw(this,void 0,void 0,function*(){const{containerId:t,methodId:i}=e;if(!i)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadPaymentMethod(i);const n=this.paymentIntegrationService.getState(),{clientToken:r,initializationData:o,config:a}=n.getPaymentMethodOrThrow(i);if(!r||!o)throw new Qi(Zi.MissingPaymentMethod);this.braintreeSdk.initialize(r);const s=yield this.braintreeSdk.getBraintreeVisaCheckout(),{currency:{code:d},cartAmount:c}=n.getCartOrThrow(),l=yield this.braintreeSdk.getVisaCheckoutSdk(a.testMode),u=s.createInitOptions({paymentRequest:{currencyCode:d,subtotal:String(c)},settings:{shipping:{collectShipping:!0}}});this.createSignInButton(t),yield l.init(u),l.on("payment.success",e=>Mw(this,void 0,void 0,function*(){yield this.paymentSuccess(s,e)}))})}deinitialize(){return Promise.resolve()}paymentSuccess(e,t){return Mw(this,void 0,void 0,function*(){return Promise.all([e.tokenize(t),this.braintreeSdk.getDataCollectorOrThrow()]).then(([e,t])=>{const i=this.paymentIntegrationService.getState(),n=i.getShippingAddress(),r=i.getBillingAddress(),{shippingAddress:o=this.toVisaCheckoutAddress(n),billingAddress:a=this.toVisaCheckoutAddress(r)}=e;return this.postForm(Object.assign(Object.assign({},e),{shippingAddress:o,billingAddress:a}),t)})})}postForm(e,t){const{userData:i,billingAddress:n,shippingAddress:r,details:o}=e,{userEmail:a}=i,{deviceData:s}=t;return this.formPoster.postForm("/checkout.php",{payment_type:e.type,nonce:e.nonce,provider:"braintreevisacheckout",action:"set_external_checkout",device_data:s,card_information:JSON.stringify({type:o.cardType,number:o.lastTwo}),billing_address:JSON.stringify(this.getAddress(a,n)),shipping_address:JSON.stringify(this.getAddress(a,r))})}toVisaCheckoutAddress(e){return e?{firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phone,streetAddress:e.address1,extendedAddress:e.address2,locality:e.city,region:e.stateOrProvinceCode,countryCode:e.countryCode,postalCode:e.postalCode}:{}}getAddress(e,t={}){return{email:e,first_name:t.firstName,last_name:t.lastName,phone_number:t.phoneNumber,address_line_1:t.streetAddress,address_line_2:t.extendedAddress,city:t.locality,state:t.region,country_code:t.countryCode,postal_code:t.postalCode}}createSignInButton(e){const t=document.querySelector(`#${e}`);if(!t)throw new Error("Need a container to place the button");return this.insertVisaCheckoutButton(t)}insertVisaCheckoutButton(e){const t=document.createElement("div");return t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="flex-end",t.innerHTML='\n <img\n alt="Visa Checkout"\n class="v-button"\n role="button"\n src="https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178"\n />\n <a class="v-learn v-learn-default" style="text-align: right; display: block; font-size: 10px; color: #003366;" href="#" data-locale="en_US">Tell Me More</a>',e.appendChild(t),t}}const Nw=Rt(e=>{const t=window,i=new bn(e),n=new Ln(new qn(a(),t,i));return new zw(e,Ee(),n)},[{id:"braintreevisacheckout"}]);function xw(e){const{billingAddress:t,email:i,firstName:n,lastName:r,phone:o,shippingAddress:a}=e,s=t||a;return{email:i,first_name:n,last_name:r,phone_number:o,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}function Fw(e){const{email:t,phone:i,shippingAddress:n}=e,r=(null==n?void 0:n.recipientName)||"",[o,a]=r.split(" ");return{email:t,first_name:o||"",last_name:a||"",phone_number:i,address_line_1:null==n?void 0:n.line1,address_line_2:null==n?void 0:n.line2,city:null==n?void 0:n.city,state:null==n?void 0:n.state,country_code:null==n?void 0:n.countryCode,postal_code:null==n?void 0:n.postalCode}}var Rw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};const Lw=e=>{const{color:t,height:i}=e;return{backgroundColor:(n=t||"",n===ho.WHITE?"#FFFFFF":"#3D95CE"),backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:`url("/app/assets/img/payment-providers/venmo-logo-${t===ho.WHITE?ho.BLUE:ho.WHITE}.svg")`,backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:`${i||40}px`,minWidth:"150px",height:"100%",width:"100%",border:t===ho.WHITE?"1px solid black":"none"};var n};class Bw{constructor(e,t,i){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeSdk=i,this.onError=V}initialize(e){return Rw(this,void 0,void 0,function*(){const{braintreevenmo:t,containerId:i,methodId:n}=e;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),{clientToken:o,initializationData:a}=r,{paymentButtonStyles:s}=a,{cartButtonStyles:d}=s||{},c=(null==t?void 0:t.style)||d;if(!o||!a)throw new Qi(Zi.MissingPaymentMethod);if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');yield this.paymentIntegrationService.loadDefaultCheckout(),this.onError=(null==t?void 0:t.onError)||this.handleError,this.braintreeSdk.initialize(o);try{const e=yield this.braintreeSdk.getVenmoCheckoutOrThrow();this.renderVenmoButton(e,i,null==t?void 0:t.buyNowInitializeOptions,c)}catch(e){(dl(e)||function(e){return e instanceof Pn}(e))&&this.handleInitializationVenmoError(e,i)}})}deinitialize(){return Rw(this,void 0,void 0,function*(){return yield this.braintreeSdk.deinitialize(),Promise.resolve()})}handleError(e){throw new Error(e.message)}createBuyNowCart(e){return Rw(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=null==e?void 0:e.getBuyNowCartRequestBody();if(!t)throw new Qi(Zi.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(t)}catch(e){throw new Zn}}})}handleInitializationVenmoError(e,t){return this.removeVenmoContainer(t),this.onError(e)}removeVenmoContainer(e){const t=document.getElementById(e);t&&t.remove()}renderVenmoButton(e,t,i,n){const r=document.getElementById(t),{color:o}=n||{};if(!r)throw new gn("Unable to create wallet button without valid container ID.");r.setAttribute("aria-label","Venmo"),Object.assign(r.style,Lw(n||{})),r.addEventListener("click",()=>Rw(this,void 0,void 0,function*(){r.setAttribute("disabled","true");const t=yield this.createBuyNowCart(i);e.tokenize&&e.tokenize((e,i)=>Rw(this,void 0,void 0,function*(){r.removeAttribute("disabled"),e&&this.onError(e),yield this.handlePostForm(i,null==t?void 0:t.id)}))})),o===ho.BLUE&&(r.addEventListener("mouseenter",()=>{r.style.backgroundColor="#0a7fc2"}),r.addEventListener("mouseleave",()=>{r.style.backgroundColor=Lw(n||{}).backgroundColor}))}handlePostForm(e,t){return Rw(this,void 0,void 0,function*(){const{deviceData:i}=yield this.braintreeSdk.getDataCollectorOrThrow(),{nonce:n,details:r}=e;this.formPoster.postForm("/checkout.php",Object.assign({nonce:n,provider:"braintreevenmo",payment_type:"paypal",device_data:i,action:"set_external_checkout",billing_address:JSON.stringify(xw(r)),shipping_address:JSON.stringify(Fw(r))},t&&{cart_id:t}))})}}const jw=Rt(e=>{const t=window,i=a(),n=new bn(e),r=new qn(i,t,n),o=new Ln(r);return new Bw(e,Ee(),o)},[{id:"braintreevenmo"}]);var Uw=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class qw{constructor(e,t){this._paymentIntegrationService=e,this._googlePayPaymentProcessor=t}initialize(e){var t,i;return Uw(this,void 0,void 0,function*(){if(!e.methodId||!Xo(e.methodId))throw new gn('Unable to proceed because "methodId" is not a valid key.');if(this._methodId=e.methodId,!e.containerId)throw new gn('Unable to proceed because "containerId" is not a valid key.');const n=e[this._getMethodOrThrow()];if(!n)throw new gn("Unable to proceed without valid options.");const{buyNowInitializeOptions:r,currencyCode:o,buttonColor:a,buttonType:s,onError:d}=n;let c,l=this._paymentIntegrationService.getState();try{c=l.getPaymentMethodOrThrow(this._getMethodOrThrow())}catch(e){l=yield this._paymentIntegrationService.loadPaymentMethod(this._getMethodOrThrow()),c=l.getPaymentMethodOrThrow(this._getMethodOrThrow())}if(this._countryCode=null===(t=c.initializationData)||void 0===t?void 0:t.storeCountry,r){if(!o)throw new gn('Unable to initialize payment because "options.currencyCode" argument is not provided.');this._currencyCode=o,this._buyNowInitializeOptions=r,yield this._googlePayPaymentProcessor.initialize(()=>c,this._getGooglePayClientOptions(),!!r,o)}else yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initialize(()=>c,this._getGooglePayClientOptions());this._paymentButton=null!==(i=this._paymentButton)&&void 0!==i?i:this._googlePayPaymentProcessor.addPaymentButton(e.containerId,{buttonColor:null!=a?a:"default",buttonType:null!=s?s:"plain",onClick:this._handleClick(d)})})}deinitialize(){var e;return null===(e=this._paymentButton)||void 0===e||e.remove(),this._paymentButton=void 0,this._methodId=void 0,Promise.resolve()}_handleClick(e){return t=>Uw(this,void 0,void 0,function*(){t.preventDefault();try{this._buyNowInitializeOptions?yield this._createBuyNowCartOrThrow(this._buyNowInitializeOptions):yield this._paymentIntegrationService.loadDefaultCheckout(),yield this._googlePayPaymentProcessor.initializeWidget(),yield this._interactWithPaymentSheet()}catch(t){let i=t;if(Zo(t)){if("CANCELED"===t.statusCode)throw new Vn;i=new Kr(JSON.stringify(t))}throw null==e||e(new Kr("An error occurred while requesting your Google Pay payment details.")),i}})}_interactWithPaymentSheet(){var e;return Uw(this,void 0,void 0,function*(){const t=yield this._googlePayPaymentProcessor.showPaymentSheet(),i=this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(t),n=this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(t),r="/embedded-checkout"===window.location.pathname?this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink:void 0;i&&(yield this._paymentIntegrationService.updateBillingAddress(i)),n&&!(null===(e=this._buyNowCart)||void 0===e?void 0:e.lineItems.digitalItems.length)&&(yield this._paymentIntegrationService.updateShippingAddress(n)),yield this._googlePayPaymentProcessor.setExternalCheckoutForm(this._getMethodOrThrow(),t,r)})}_getGooglePayClientOptions(){return{paymentDataCallbacks:{onPaymentDataChanged:({callbackTrigger:e,shippingAddress:t,shippingOptionData:i,offerData:n})=>Uw(this,void 0,void 0,function*(){const{availableTriggers:r,addressChangeTriggers:o,shippingOptionsChangeTriggers:a,offerChangeTriggers:s}=this._googlePayPaymentProcessor.getCallbackTriggers();if(!r.includes(e))return;const d=o.includes(e)?yield this._googlePayPaymentProcessor.handleShippingAddressChange(t):void 0;a.includes(e)&&(yield this._googlePayPaymentProcessor.handleShippingOptionChange(i.id));const{newOfferInfo:c,error:l}=s.includes(e)?yield this._googlePayPaymentProcessor.handleCoupons(n):{},u=l;return this._buyNowInitializeOptions?this._getBuyNowTransactionInfo(d,c,u):this._getTransactionInfo(d,c,u)})}}}_createBuyNowCartOrThrow(e){return Uw(this,void 0,void 0,function*(){if("function"==typeof(null==e?void 0:e.getBuyNowCartRequestBody)){const t=e.getBuyNowCartRequestBody();try{this._buyNowCart=yield this._paymentIntegrationService.createBuyNowCart(t),yield this._paymentIntegrationService.loadCheckout(this._buyNowCart.id)}catch(e){if("string"==typeof e)throw new Zn(e);throw e}}})}_getBuyNowTransactionInfo(e,t,i){if(!this._buyNowCart)return;const{cartAmount:n}=this._buyNowCart,r=this._googlePayPaymentProcessor.getTotalPrice();return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:this._getCurrencyCodeOrThrow(),totalPrice:r||String(n),totalPriceStatus:qo.FINAL})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),i&&{error:i})}_getTransactionInfo(e,t,i){return Uw(this,void 0,void 0,function*(){yield this._paymentIntegrationService.loadCheckout();const n=this._googlePayPaymentProcessor.getTotalPrice(),{code:r}=this._paymentIntegrationService.getState().getCartOrThrow().currency;return Object.assign(Object.assign(Object.assign({newTransactionInfo:Object.assign(Object.assign({},this._countryCode&&{countryCode:this._countryCode}),{currencyCode:r,totalPriceStatus:qo.FINAL,totalPrice:n})},e&&{newShippingOptionParameters:e}),t&&{newOfferInfo:t}),i&&{error:i})})}_getMethodOrThrow(){return tn(this._methodId,()=>new nn(Xi.PaymentNotInitialized))}_getCurrencyCodeOrThrow(){return tn(this._currencyCode,()=>new gn('Unable to initialize payment because "options.currencyCode" argument is not provided.'))}}const Vw=Rt(e=>{const t=i(),n=window,r=new bn(e),o=new Ln(new qn(a(),n,r));return new qw(e,new ia(ra(),new Ua(e,o),t,Ee()))},[{id:"googlepaybraintree"}]),Gw=Rt(e=>new qw(e,new ia(ra(),new Wa(e,new Ga(a())),i(),Ee())),[{id:"googlepaypaypalcommerce"}]),Hw=Rt(e=>new qw(e,new ia(ra(),new Ja(e,new Mr(a())),i(),Ee())),[{id:"googlepay_bigcommerce_payments"}]),$w=Rt(e=>{const t=i();return new qw(e,new ia(ra(),new Jo("adyen",e),t,Ee()))},[{id:"googlepayadyenv2"}]),Ww=Rt(e=>{const t=i();return new qw(e,new ia(ra(),new Jo("adyen",e),t,Ee()))},[{id:"googlepayadyenv3"}]),Yw=Rt(e=>new qw(e,new ia(ra(),new sa(e),i(),Ee())),[{id:"googlepayauthorizenet"}]),Kw=Rt(e=>{const t=i();return new qw(e,new ia(ra(),new ha(e,t),t,Ee()))},[{id:"googlepaycheckoutcom"}]),Jw=Rt(e=>new qw(e,new ia(ra(),new ma(e),i(),Ee())),[{id:"googlepaycybersourcev2"},{id:"googlepaybnz"}]),Zw=Rt(e=>new qw(e,new ia(ra(),new va(e),i(),Ee())),[{id:"googlepayorbital"}]),Xw=Rt(e=>new qw(e,new ia(ra(),new xa(e,new ka(a())),i(),Ee())),[{id:"googlepaystripe"},{id:"googlepaystripeupe"},{id:"googlepaystripeocs"}]),Qw=Rt(e=>new qw(e,new ia(ra(),new La(e),i(),Ee())),[{id:"googlepayworldpayaccess"}]),eI=Rt(e=>new qw(e,new ia(ra(),new es(e,Ee()),i(),Ee())),[{id:"googlepaytdonlinemart"}]);var tI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class iI{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){var t;return tI(this,void 0,void 0,function*(){const{paypalcommerce:i,containerId:n,methodId:r}=e,o=Boolean(null==i?void 0:i.buyNowInitializeOptions);if(!r)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(o&&!i.currencyCode)throw new gn('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=i.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');o||(yield this.paymentIntegrationService.loadDefaultCheckout());const a=o?i.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalCommerceIntegrationService.loadPayPalSdk(r,a,!1),this.renderButton(n,r,i,o)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i,n){var r,o;const{buyNowInitializeOptions:a,style:s,onComplete:d,onEligibilityFailure:c}=i,l=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),u=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:h,isAppSwitchEnabled:p}=u.initializationData||{},m=Object.assign(Object.assign({},!n&&this.isPaypalCommerceAppSwitchEnabled(t)&&{appSwitchWhenAvailable:!0}),{createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommerce"),onApprove:({orderID:e})=>this.paypalCommerceIntegrationService.tokenizePayment(t,e)}),y={onClick:()=>this.handleClick(a),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},g=Object.assign(Object.assign({},!p&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,d)}),v=Object.assign(Object.assign(Object.assign({fundingSource:l.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(s)},m),a&&y),h&&g),f=l.Buttons(v);f.isEligible()?(null===(r=f.hasReturned)||void 0===r?void 0:r.call(f))&&this.isPaypalCommerceAppSwitchEnabled(t)?null===(o=f.resume)||void 0===o||o.call(f):f.render(`#${e}`):c&&"function"==typeof c?c():this.paypalCommerceIntegrationService.removeElement(e)}handleClick(e){return tI(this,void 0,void 0,function*(){if(e){const t=yield this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return tI(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.paypalCommerceIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return tI(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){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return tI(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){if("string"==typeof e)throw new Error(e);throw e}})}isPaypalCommerceAppSwitchEnabled(e){var t;return(null===(t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData)||void 0===t?void 0:t.isAppSwitchEnabled)||!1}}const nI=Rt(e=>new iI(e,ys(e)),[{id:"paypalcommerce"}]);var rI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class oI{constructor(e,t,i){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.paypalCommerceSdk=i}initialize(e){var t;return rI(this,void 0,void 0,function*(){const{paypalcommercecredit:i,containerId:n,methodId:r}=e,{buyNowInitializeOptions:o,currencyCode:a,messagingContainerId:s}=i||{},d=!!o;if(!r)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(d&&!a)throw new gn('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(d&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');d||(yield this.paymentIntegrationService.loadDefaultCheckout());const c=this.paymentIntegrationService.getState(),l=d?a:c.getCartOrThrow().currency.code;yield this.paypalCommerceIntegrationService.loadPayPalSdk(r,l,!1),this.renderButton(n,r,i);const u=c.getStoreConfigOrThrow().checkoutSettings.features;if(null!==(t=u["PAYPAL-5557.Hide_ppc_banner_implementation"])&&void 0!==t&&t)return;const h=s&&document.getElementById(s);if(l&&h){const e=c.getPaymentMethodOrThrow(r),{paypalBNPLConfiguration:t=[]}=e.initializationData||{},i=t&&t.find(({id:e})=>"cart"===e);if(!(null==i?void 0:i.status))return;h.removeAttribute("data-pp-style-logo-type"),h.removeAttribute("data-pp-style-logo-position"),h.removeAttribute("data-pp-style-text-color"),h.removeAttribute("data-pp-style-text-size");const n=yield this.paypalCommerceSdk.getPayPalMessages(e,l);this.renderMessages(n,s,i)}})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:r,onComplete:o,onEligibilityFailure:a}=i,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),d=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),{isHostedCheckoutEnabled:c,isAppSwitchEnabled:l}=d.initializationData||{},u={createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercecredit"),onApprove:({orderID:e})=>this.paypalCommerceIntegrationService.tokenizePayment(t,e)},h={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},p=Object.assign(Object.assign({},!l&&{onShippingAddressChange:e=>this.onShippingAddressChange(e),onShippingOptionsChange:e=>this.onShippingOptionsChange(e)}),{onApprove:(e,i)=>this.onHostedCheckoutApprove(e,i,t,o)}),m=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT];let y=!1;m.forEach(t=>{if(!y){const i=Object.assign(Object.assign(Object.assign({fundingSource:t,style:this.paypalCommerceIntegrationService.getValidButtonStyle(r)},u),n&&h),c&&p),o=s.Buttons(i);o.isEligible()?(o.render(`#${e}`),y=!0):a&&"function"==typeof a&&a()}}),y||this.paypalCommerceIntegrationService.removeElement(e)}handleClick(e){return rI(this,void 0,void 0,function*(){if(e){const t=yield this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}onHostedCheckoutApprove(e,t,i,n){return rI(this,void 0,void 0,function*(){if(!e.orderID)throw new Qi(Zi.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()}return yield this.paymentIntegrationService.submitOrder({},{params:{methodId:i}}),yield this.paypalCommerceIntegrationService.submitPayment(i,e.orderID),n&&"function"==typeof n&&n(),!0}catch(e){if("string"==typeof e)throw new Error(e);throw e}})}onShippingAddressChange(e){return rI(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){if("string"==typeof e)throw new Error(e);throw e}})}onShippingOptionsChange(e){return rI(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){if("string"==typeof e)throw new Error(e);throw e}})}renderMessages(e,t,i){const n={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:Lh(i)};e.Messages(n).render(`#${t}`)}}const aI=Rt(e=>new oI(e,ys(e),qh()),[{id:"paypalcommercecredit"}]);var sI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class dI{constructor(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}initialize(e){return sI(this,void 0,void 0,function*(){const{paypalcommercevenmo:t,containerId:i,methodId:n}=e,{buyNowInitializeOptions:r,currencyCode:o}=t||{},a=!!r;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(a&&!o)throw new gn('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null==r?void 0:r.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');a||(yield this.paymentIntegrationService.loadDefaultCheckout());const s=a?o:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalCommerceIntegrationService.loadPayPalSdk(n,s,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{buyNowInitializeOptions:n,style:r,onEligibilityFailure:o}=i,a=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),s=a.FUNDING.VENMO,d={createOrder:()=>this.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo"),onApprove:({orderID:e})=>this.paypalCommerceIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(n),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:s,style:this.getValidVenmoButtonStyles(r)},d),n&&c),u=a.Buttons(l);u.isEligible()?u.render(`#${e}`):o&&"function"==typeof o?o():this.paypalCommerceIntegrationService.removeElement(e)}getValidVenmoButtonStyles(e){const t=this.paypalCommerceIntegrationService.getValidButtonStyle(e);return t.color===os.gold?Object.assign(Object.assign({},t),{color:void 0}):t}handleClick(e){return sI(this,void 0,void 0,function*(){if(e){const t=yield this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const cI=Rt(e=>new dI(e,ys(e)),[{id:"paypalcommercevenmo"}]);var lI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class uI{constructor(e,t){this.paymentIntegrationService=e,this.paypalIntegrationService=t}initialize(e){return lI(this,void 0,void 0,function*(){const{paypalcommercealternativemethods:t,containerId:i,methodId:n}=e,{apm:r,buyNowInitializeOptions:o,currencyCode:a}=t||{},s=!!o;if(!n)throw new gn('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new gn('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new gn('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');if(!r)throw new gn('Unable to initialize payment because "options.paypalcommercealternativemethods.apm" argument is not provided.');if(s&&!a)throw new gn('Unable to initialize payment because "options.paypalcommercealternativemethods.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new gn('Unable to initialize payment because "options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');s||(yield this.paymentIntegrationService.loadDefaultCheckout());const d=s?a:this.paymentIntegrationService.getState().getCartOrThrow().currency.code;yield this.paypalIntegrationService.loadPayPalSdk(n,d,!1),this.renderButton(i,n,t)})}deinitialize(){return Promise.resolve()}renderButton(e,t,i){const{apm:n,buyNowInitializeOptions:r,style:o,onEligibilityFailure:a}=i,s=this.paypalIntegrationService.getPayPalSdkOrThrow();if(!Object.values(s.FUNDING).includes(n))throw new gn('Unable to initialize PayPal button because "options.paypalcommercealternativemethods.apm" argument is not valid funding source.');const d={createOrder:()=>this.paypalIntegrationService.createOrder("paypalcommercealternativemethod"),onApprove:({orderID:e})=>this.paypalIntegrationService.tokenizePayment(t,e)},c={onClick:()=>this.handleClick(r),onCancel:()=>this.paymentIntegrationService.loadDefaultCheckout()},l=Object.assign(Object.assign({fundingSource:n,style:this.paypalIntegrationService.getValidButtonStyle(o)},d),r&&c),u=s.Buttons(l);u.isEligible()?u.render(`#${e}`):a&&"function"==typeof a?a():this.paypalIntegrationService.removeElement(e)}handleClick(e){return lI(this,void 0,void 0,function*(){if(e){const t=yield this.paypalIntegrationService.createBuyNowCartOrThrow(e);yield this.paymentIntegrationService.loadCheckout(t.id)}})}}const hI=Rt(e=>new uI(e,Qh(e)),[{id:"paypalcommercealternativemethods"}]);var pI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class mI{constructor(e,t,i){this.paymentIntegrationService=e,this.paypalExpressScriptLoader=t,this.formPoster=i}initialize(e){return pI(this,void 0,void 0,function*(){const t=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!e.paypal)throw new gn;if(!t.config.merchantId)throw new Qi(Zi.MissingPaymentMethod);const i=yield this.paypalExpressScriptLoader.loadPaypalSDK(t.config.merchantId);this.renderButton(e,i)})}deinitialize(){return Promise.resolve()}renderButton(e,t){const{containerId:i,methodId:n,paypal:r}=e,{allowCredit:o,clientId:a,onPaymentError:s,shouldProcessPayment:d,style:c}=r,l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!l.config.merchantId)throw new Qi(Zi.MissingPaymentMethod);const u=l.config.merchantId,h=l.config.testMode?"sandbox":"production",p={[h]:a},m=t.FUNDING.CREDIT||"credit",y=o?[m]:[],g=o?[]:[m];return t.Button.render({env:h,client:p,commit:d,funding:{allowed:y,disallowed:g},style:this.getStyle(c),payment:(e,t)=>this.setupPayment(u,t,s),onAuthorize:(e,t)=>this.tokenizePayment(e,n,t,d)},i)}getStyle(e){const{color:t,fundingicons:i,label:n,layout:r,shape:o,size:a,tagline:s}=e||{};return{color:t,fundingicons:i,label:n,layout:r,shape:o||vp.RECT,size:"small"===a?mp.RESPONSIVE:a,tagline:s}}setupPayment(e,t,i){return pI(this,void 0,void 0,function*(){if(!t)throw new nn(Xi.CheckoutButtonNotInitialized);try{const i=yield this.paymentIntegrationService.loadDefaultCheckout(),{id:n}=i.getCartOrThrow(),r=i.getHost()||"";return(yield t.request.post(`${r}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:n},{headers:Object.assign({"X-API-INTERNAL":cr},hr)})).id}catch(e){throw i&&e instanceof Ji&&i(e),e}})}tokenizePayment(e,t,i,n){return pI(this,void 0,void 0,function*(){if(!i)throw new nn(Xi.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new Qi(Zi.MissingPayment);const r=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t),o=yield i.payment.get(e.paymentID);return this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r.id,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(o.payer.payer_info)})})}}const yI=Rt(e=>new mI(e,new Ip(a()),Ee()),[{id:"paypalexpress"}]);var gI=function(e,t,i,n){return new(i||(i=Promise))(function(r,o){function a(e){try{d(n.next(e))}catch(e){o(e)}}function s(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,s)}d((n=n.apply(e,t||[])).next())})};class vI{constructor(e,t,i,n){this.paymentIntegrationService=e,this.scriptLoader=t,this.stripeIntegrationService=i,this.loadingIndicator=n}initialize(e){return gI(this,void 0,void 0,function*(){const{stripeocs:t,containerId:i}=e||{};if(!t||!i)throw new nn(Xi.PaymentNotInitialized);const{methodId:n,gatewayId:r}=t;if(!n||!r)throw new Qi(Zi.MissingPaymentMethod);const o=yield this.paymentIntegrationService.loadPaymentMethod(r,{params:{method:n}}),a=o.getPaymentMethodOrThrow(n,r),{loadingContainerId:s,buttonHeight:d,onComplete:c}=t;if(this._loadingIndicatorContainer=s,this._onComplete=c,!$s(a))throw new Qi(Zi.MissingPaymentMethod);const{initializationData:l}=a,{captureMethod:u}=l,h=this.stripeIntegrationService.getStripeJsVersion(l);return this._captureMethod=u,this._stripeClient=yield this.scriptLoader.getStripeClient(l,o.getCartLocale(),h),yield this.paymentIntegrationService.loadDefaultCheckout(),yield this._mountExpressCheckoutElement(n,i,this._stripeClient,d),Promise.resolve()})}signIn(){return Promise.resolve()}signOut(){return Promise.resolve()}executePaymentMethodCheckout(){return Promise.resolve()}deinitialize(){return Promise.resolve()}_mountExpressCheckoutElement(e,t,i,n=40){return gI(this,void 0,void 0,function*(){const r=this._shouldRequireShippingAddress(),o=Object.assign(Object.assign(Object.assign({shippingAddressRequired:r},r?{allowedShippingCountries:yield this._getAvailableCountries()}:{}),r?{shippingRates:[{id:"_",amount:0,displayName:"Pending rates"}]}:{}),{billingAddressRequired:!0,emailRequired:!0,phoneNumberRequired:!0,paymentMethods:{link:Ca.AUTO,applePay:Ca.NEVER,googlePay:Ca.NEVER,amazonPay:Ca.NEVER,paypal:Ca.NEVER,klarna:Ca.NEVER},buttonHeight:n}),{cartAmount:a=1}=this.paymentIntegrationService.getState().getCart()||{},s=Object.assign({mode:"payment",amount:this._toCents(a),currency:this._getCurrency()},this._captureMethod?{captureMethod:this._captureMethod}:{});this._stripeElements=i.elements(s),this._linkV2Element=this._stripeElements.create(Pa.EXPRESS_CHECKOUT,o),this._linkV2Element.mount(`#${t}`),this._initializeEvents(this._linkV2Element,e)})}_initializeEvents(e,t){this._shouldRequireShippingAddress()&&(e.on(Ea.SHIPPING_ADDRESS_CHANGE,e=>gI(this,void 0,void 0,function*(){return this._onShippingAddressChange(e)})),e.on(Ea.SHIPPING_RATE_CHANGE,e=>gI(this,void 0,void 0,function*(){return this._onShippingRateChange(e)}))),e.on(Ea.CONFIRM,e=>gI(this,void 0,void 0,function*(){return this._onConfirm(e,t)})),e.on(Ea.CANCEL,this._onCancel)}_onShippingAddressChange(e){return gI(this,void 0,void 0,function*(){if(!("address"in e))return;const t=e.address,i={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(i);const n=yield this._getAvailableShippingOptions();yield this._updateDisplayedPrice(),(null==n?void 0:n.length)?e.resolve({shippingRates:n}):e.reject()})}_onCancel(){throw new Vn}_onShippingRateChange(e){return gI(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 gI(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 i=this._getPaymentPayload(t);try{yield this.paymentIntegrationService.submitPayment(i)}catch(e){yield this._processAdditionalAction(e,t)}}return Promise.resolve()})}_updateShippingAndBillingAddress(e){var t,i,n,r,o,a,s,d;return gI(this,void 0,void 0,function*(){const c=this._shouldRequireShippingAddress(),l=(null===(i=null===(t=e.shippingAddress)||void 0===t?void 0:t.name)||void 0===i?void 0:i.split(" ")[0])||(null===(r=null===(n=e.billingDetails)||void 0===n?void 0:n.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,i,n){var r,o,a,s,d,c,l;return{firstName:i,lastName:n,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,i,n){var r,o,a,s,d,c;return{email:(null==t?void 0:t.email)||"",firstName:i,lastName:n,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 gI(this,void 0,void 0,function*(){if(!ca(e)||!this.stripeIntegrationService.isAdditionalActionError(e.body.errors))throw e;if(!this._stripeClient||!this._stripeElements)throw new nn(Xi.PaymentNotInitialized);const{data:i}=e.body.additional_action_required,{token:n}=i,{paymentIntent:r}=yield this._confirmStripePaymentOrThrow(i,t),o=this._getPaymentPayload(t,(null==r?void 0:r.id)||n);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 i,n,r;return gI(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===(i=this._stripeClient)||void 0===i?void 0:i.confirmPayment({elements:s.elements,clientSecret:o,redirect:Ca.IF_REQUIRED,confirmParams:{return_url:null===(n=s.confirmParams)||void 0===n?void 0:n.return_url}});if(d=null==e?void 0:e.error,d||!(null==e?void 0:e.paymentIntent))throw new Kr;return e}catch(e){return this.stripeIntegrationService.throwStripeError(d)}})}_completeCheckoutFlow(){return gI(this,void 0,void 0,function*(){return"function"==typeof this._onComplete?this._onComplete():(window.location.replace("/checkout/order-confirmation"),Promise.resolve())})}_getPaymentPayload(e,t){var i;const n=(null===(i=this.paymentIntegrationService.getState().getCart())||void 0===i?void 0:i.id)||"";return{methodId:e,paymentData:{formattedPayload:Object.assign(Object.assign({cart_id:n},t?{credit_card_token:{token:t}}:{}),{confirm:!1,method:_a.Link})}}}_shouldRequireShippingAddress(){const{getCart:e}=this.paymentIntegrationService.getState(),{lineItems:t}=e()||{};return!!(null==t?void 0:t.physicalItems.length)}_updateDisplayedPrice(){return gI(this,void 0,void 0,function*(){this._stripeElements&&this._stripeElements.update({currency:this._getCurrency(),mode:"payment",amount:yield this._getTotalPrice()})})}_getCurrency(){var e;if(!this._currencyCode){const t=null===(e=this.paymentIntegrationService.getState().getCart())||void 0===e?void 0:e.currency;t&&(this._currencyCode=t.code.toLowerCase())}return this._currencyCode}_getTotalPrice(){var e;return gI(this,void 0,void 0,function*(){yield this.paymentIntegrationService.loadCheckout();const{getCheckoutOrThrow:t,getCart:i}=this.paymentIntegrationService.getState(),{decimalPlaces:n}=(null===(e=i())||void 0===e?void 0:e.currency)||{},r=J(t().outstandingBalance,n).toFixed(n);return this._toCents(+r)})}_getAvailableCountries(){var e;return gI(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=>nd.includes(e))})}_getAvailableShippingOptions(){var e,t;return gI(this,void 0,void 0,function*(){const i=this.paymentIntegrationService.getState().getConsignments();if(!(null==i?void 0:i[0]))return;const n=i[0],r=(n.availableShippingOptions||[]).map(this._getStripeShippingOption.bind(this)),o=null===(e=n.selectedShippingOption)||void 0===e?void 0:e.id;return o?r.sort(e=>e.id===o?-1:0):yield this._handleShippingOptionChange(null===(t=r[0])||void 0===t?void 0:t.id),r})}_getStripeShippingOption({id:e,cost:t,description:i}){return{id:e,displayName:i,amount:this._toCents(t)}}_handleShippingOptionChange(e){return gI(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 id(t.decimalPlaces):void 0}_toCents(e){const t=Math.round(100*e),i=this._getAmountTransformer();return i?i.toInteger(e):t}_toggleLoadingIndicator(e){e&&this._loadingIndicatorContainer?this.loadingIndicator.show(this._loadingIndicatorContainer):this.loadingIndicator.hide()}}const fI=Rt(e=>{const t=new ka(a()),i=new td({containerStyles:Qs});return new vI(e,t,new Zs(e,t),i)},[{id:"stripeocs"}]),SI=e=>{const t=ie(e);return document.getElementById(t)?SI(e):t};function wI(e){return Object.prototype.hasOwnProperty.call(e,"cacheKey")}class II{constructor(e){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=Object.assign({maxSize:0,isEqual:Be,onExpire:V},e)}getKey(...e){const t=this._resolveMap(...e),{index:i,parentMap:n}=t;let{map:r}=t;return r&&r.cacheKey?r.usedCount++:r=this._generateMap(n,e.slice(i)),this._removeLeastUsedMap(r),r.cacheKey}getUsedCount(...e){const{map:t}=this._resolveMap(...e);return t?t.usedCount:0}_resolveMap(...e){let t=0,i=this._map;for(;i.maps.length;){let n=!1;for(let r=0;r<i.maps.length;r++){const o=i.maps[r];if(this._options.isEqual(o.value,e[t])){if(i.maps.unshift(...i.maps.splice(r,1)),(0===e.length||t===e.length-1)&&wI(o))return{index:t,map:o,parentMap:i};n=!0,i=o,t++;break}}if(!n)break}return{index:t,parentMap:i}}_generateMap(e,t){let i,n=0,r=e;do{i={maps:[],parentMap:r,usedCount:1,value:t[n]},r.maps.unshift(i),r=i,n++}while(n<t.length);const o=i;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 i=this._usedMaps.pop();i&&(this._removeMap(i),this._options.onExpire(i.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 _I(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(i=>{const n=Object.getOwnPropertyDescriptor(e.prototype,i);n&&"constructor"!==i&&Object.defineProperty(t.prototype,i,function(e,t,i){if("function"!=typeof i.value)return i;let n=new II,r=i.value,o=Pe(r);return xi(e,t,{get(){const e=(...e)=>{const t=o.call(this,...e);if(1===n.getUsedCount(...e))return t;const i=r.call(this,...e);return mv(i,t,{keyFilter:e=>!function(e){return 0===`${e}`.indexOf("$$")||0===`${e}`.indexOf("_")}(e)})?t:(o.cache.set(n.getKey(...e),i),i)};return Object.defineProperty(this,t,Object.assign(Object.assign({},i),{value:e})),e},set(e){n=new II,r=e,o=Pe(r)}})}(e.prototype,i,n))}),t}let CI=class{constructor(e){this._checkoutButton=e.checkoutButton}getInitializeButtonError(e){return this._checkoutButton.getInitializeError(e)}getDeinitializeButtonError(e){return this._checkoutButton.getDeinitializeError(e)}};CI=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([_I],CI);const bI=CI;let PI=class{constructor(e){this._checkoutButton=e.checkoutButton}isInitializingButton(e){return this._checkoutButton.isInitializing(e)}isDeinitializingButton(e){return this._checkoutButton.isDeinitializing(e)}};PI=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([_I],PI);const OI=PI;function EI(e){return{errors:new bI(e),statuses:new OI(e)}}let AI=class{constructor(e,t){this._store=e,this._buttonStrategyActionCreator=t,this._state=EI(this._store.getState()),this._store.subscribe(e=>{this._state=EI(e)})}getState(){return this._state}subscribe(e,...t){return this._store.subscribe(()=>e(this.getState()),e=>e.checkoutButton.getState(),...t.map(e=>t=>e(EI(t))))}initializeButton(e){const t=(i=e.containerId,/^\w[\w\-\:\.]*$/.test(i)?[e.containerId]:function(e,t){const i=document.querySelectorAll(e);if(!i.length)throw new Lt(`Unable to find any element with the specified selector: ${e}`);return Array.prototype.slice.call(i).map(e=>(e.id||(e.id=SI(t)),e.id))}(e.containerId,`${e.methodId}-container`));var i;return Promise.all(t.map(t=>{const i=this._buttonStrategyActionCreator.initialize(Object.assign(Object.assign({},e),{containerId:t})),n=`checkoutButtonStrategy:${e.methodId}:${t}`;return this._store.dispatch(i,{queueId:n})})).then(()=>this.getState())}deinitializeButton(e){const t=this._buttonStrategyActionCreator.deinitialize(e),i=`checkoutButtonStrategy:${e.methodId}`;return this._store.dispatch(t,{queueId:i}).then(()=>this.getState())}};AI=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],AI);const TI=AI;class kI{constructor(e,t,i){this._registry=e,this._registryV2=t,this._paymentMethodActionCreator=i}initialize(e){return t=>{const i={methodId:e.methodId,containerId:e.containerId};if(t.getState().checkoutButton.isInitialized(e.methodId,e.containerId))return ce();const n=e.currencyCode?{params:{currencyCode:e.currencyCode}}:{},r=Object.assign(Object.assign({},n),{timeout:e.timeout,useCache:!0});return se(me(l(Tv.InitializeButtonRequested,void 0,i)),this._paymentMethodActionCreator.loadPaymentMethod(e.methodId,r)(t),de(()=>this._getStrategy(e.methodId).initialize(e).then(()=>l(Tv.InitializeButtonSucceeded,void 0,i)))).pipe(ge(e=>Je(Tv.InitializeButtonFailed,e,i)))}}deinitialize(e){return t=>{const i={methodId:e.methodId};return t.getState().checkoutButton.isInitialized(e.methodId)?se(me(l(Tv.DeinitializeButtonRequested,void 0,i)),de(()=>this._getStrategy(e.methodId).deinitialize().then(()=>l(Tv.DeinitializeButtonSucceeded,void 0,i)))).pipe(ge(e=>Je(Tv.DeinitializeButtonFailed,e,i))):ce()}}_getStrategy(e){let t;try{t=this._registryV2.get({id:e})}catch(i){t=this._registry.get(e)}return t}}class DI extends Ze{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 MI,zI,NI,xI,FI,RI,LI,BI;class jI{constructor(e){this._scriptLoader=e,this._window=window}loadPaypal(e=""){return t=this,i=void 0,r=function*(){const t="//www.paypalobjects.com/api/checkout.min.js",i={async:!0,attributes:{"data-merchant-id":e}};if(e?yield this._scriptLoader.loadScript(t,i):yield this._scriptLoader.loadScript(t),!this._window.paypal)throw new DI;return this._window.paypal},new((n=void 0)||(n=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 i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(a,s)}d((r=r.apply(t,i||[])).next())});var t,i,n,r}}!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(MI||(MI={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(zI||(zI={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black",e.WHITE="white"}(NI||(NI={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(xI||(xI={})),function(e){e.PILL="pill",e.RECT="rect"}(FI||(FI={}));class UI{constructor(e,t,i,n,r=""){this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=i,this._formPoster=n,this._host=r}initialize(e){const t=e.paypal,i=this._store.getState(),n=this._paymentMethod=i.paymentMethods.getPaymentMethod(e.methodId);if(!t)throw new Lt;if(!n)throw new Xe(We.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(n.config.merchantId).then(i=>{var r,o;if(!n||!n.config.merchantId)throw new Xe(We.MissingPaymentMethod);const a=n.config.merchantId,s=n.config.testMode?"sandbox":"production",d={[s]:t.clientId},c=i.FUNDING.CREDIT||"credit",l=t.allowCredit?[c]:[],u=t.allowCredit?[]:[c];return i.Button.render({env:s,client:d,commit:t.shouldProcessPayment,funding:{allowed:l,disallowed:u},style:Object.assign(Object.assign({shape:FI.RECT},W(t.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===n.id&&"small"===(null===(r=t.style)||void 0===r?void 0:r.size)?zI.RESPONSIVE:null===(o=t.style)||void 0===o?void 0:o.size}),payment:(e,i)=>this._setupPayment(a,i,t.onPaymentError),onAuthorize:(e,i)=>this._tokenizePayment(e,i,t.shouldProcessPayment,t.onAuthorizeError)},e.containerId)})}deinitialize(){return this._paymentMethod=void 0,Promise.resolve()}_setupPayment(e,t,i){if(!t)throw new pi(si.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then(i=>{const n=i.cart.getCart(),r=n?n.id:"";return t.request.post(`${this._host}/api/storefront/payment/paypalexpress`,{merchantId:e,cartId:r},{headers:Object.assign({"X-API-INTERNAL":Ct},rt)})}).then(e=>e.id).catch(e=>{throw i&&i(e),e})}_tokenizePayment(e,t,i,n){if(!this._paymentMethod)throw new pi(si.CheckoutButtonNotInitialized);if(!t)throw new pi(si.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new Xe(We.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:i?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})})}}function qI(e){const{host:t}=null!=e?e:{},n=ZS({config:{meta:{host:null==e?void 0:e.host,locale:null==e?void 0:e.locale},errors:{},statuses:{}}}),r=i({host:t}),o=Ee({host:t}),s=function(e,t){const i=new jt;for(const[,n]of Object.entries(t))if(Ft(n))for(const t of n.resolveIds)i.register(t,()=>n(e));return i}(Ng(n),Ke);return new TI(n,new kI(function(e,t,i,n){const r=new Bt,o=a(),s=new Qt(t),d=new ti(s,new St(new bt(t)),new ni(new ri(t)));return r.register(wy.PAYPALEXPRESS,()=>new UI(e,d,new jI(o),i,n)),r}(n,r,o,t),s,new zm(new Nm(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"}(RI||(RI={}));class VI extends It{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"}(LI||(LI={}));class GI extends Ze{constructor(e,t=LI.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"}(BI||(BI={}));const HI="isCookieAllowed",$I="lastAllowCookieAttempt";let WI=class{constructor(e,t,i,n,r,o,a,s){this._iframeCreator=e,this._messageListener=t,this._messagePoster=i,this._loadingIndicator=n,this._requestSender=r,this._storage=o,this._location=a,this._options=s,this._isAttached=!1,this._options.onComplete&&this._messageListener.addListener(RI.CheckoutComplete,this._options.onComplete),this._options.onError&&this._messageListener.addListener(RI.CheckoutError,this._options.onError),this._options.onLoad&&this._messageListener.addListener(RI.CheckoutLoaded,this._options.onLoad),this._options.onFrameLoad&&this._messageListener.addListener(RI.FrameLoaded,this._options.onFrameLoad),this._options.onSignOut&&this._messageListener.addListener(RI.SignedOut,this._options.onSignOut),this._messageListener.addListener(RI.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:RI.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:BI.StyleConfigured,payload:this._options.styles}))}_attemptLogin(){return/^\/login\/token/.test(wi(this._options.url).pathname)?this._requestSender.post(this._options.url).then(({body:{redirectUrl:e}})=>e).catch(e=>Promise.reject(new VI(e))):Promise.resolve(this._options.url)}_allowCookie(){if(this._storage.getItem(HI))return Promise.resolve();this._storage.setItem(HI,!0),this._storage.setItem($I,Date.now());const{origin:e}=wi(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($I));return(!t||Date.now()-t>6e5)&&e instanceof GI&&e.subtype===LI.MissingContent?(this._storage.removeItem($I),this._storage.removeItem(HI),this._allowCookie()):Promise.reject()}};WI=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],WI);const YI=WI;class KI{constructor(e){this._options=e}createFrame(e,t){const i=document.getElementById(t),{timeout:n=6e4}=this._options||{};if(!i)throw new GI("Unable to embed the iframe because the container element could not be found.",LI.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",i.appendChild(r),this._toResizableFrame(r,n).catch(e=>{throw i.removeChild(r),e})}_toResizableFrame(e,t){return new Promise((i,n)=>{const r=window.setTimeout(()=>{n(new GI("Unable to embed the iframe because the content could not be loaded."))},t),o=t=>{if((t.origin===wi(e.src).origin||t.origin===Gi(wi(e.src)).origin)&&(_i(t.data,RI.FrameError)&&(a(),n(new GI(t.data.payload.message,LI.MissingContent))),_i(t.data,RI.FrameLoaded))){e.style.display="";const n=Ti({scrolling:!1,sizeWidth:!1,heightCalculationMethod:t.data.payload&&t.data.payload.contentId?"taggedElement":"lowestElement"},e);a(),i(n[n.length-1])}},a=()=>{window.removeEventListener("message",o),window.clearTimeout(r)};window.addEventListener("message",o)})}}function JI(e){const t=wi(e.url).origin;return new YI(new KI,new $i(t),new Ci(t),new td({styles:e.styles&&e.styles.loadingIndicator}),i(),new Gm("BigCommerce.EmbeddedCheckout"),window.location,e).attach()}function ZI(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 XI(e){return"object"==typeof e&&null!==e&&"message"in e&&"type"in e}let QI=class{constructor(e,t,i,n={}){this._messageListener=e,this._messagePoster=t,this._untargetedMessagePoster=i,this._messageHandlers=n,this._messageListener.listen()}postComplete(){const e={type:RI.CheckoutComplete};this._postMessage(e)}postError(e){const t={type:RI.CheckoutError,payload:this._transformError(e)};this._postMessage(t)}postFrameError(e){const t={type:RI.FrameError,payload:this._transformError(e)};this._postMessage(t,{untargeted:!0})}postFrameLoaded(e){const t={type:RI.FrameLoaded,payload:e};this._postMessage(t)}postLoaded(){const e={type:RI.CheckoutLoaded};this._postMessage(e)}postSignedOut(){const e={type:RI.SignedOut};this._postMessage(e)}receiveStyles(e){this._messageListener.addListener(BI.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 i=this._messageHandlers[t];i&&i.call(null,e)})}_transformError(e){return{message:e.message,type:XI(e)?e.type:void 0,subtype:XI(e)?e.subtype:void 0}}};QI=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],QI);const e_=QI;let t_=class{postComplete(){}postError(){}postFrameError(){}postFrameLoaded(){}postLoaded(){}postSignedOut(){}receiveStyles(){}};t_=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],t_);const i_=t_;function n_(e){Ge(939);const t=e.parentWindow||window.parent;return window===t?new i_:new e_(new $i(e.parentOrigin),new Ci(e.parentOrigin,t),new Ci("*",t),{[RI.FrameLoaded]:ZI})}const r_="en",o_="optimized_checkout";let a_=class{constructor(e,t){var i;this._logger=t;const{locale:n,locales:r,translations:o}=this._transformConfig(e);this._locale=n,this._locales=r,this._translations=o,this._formatters={},this._isCspNonceExperimentEnabled=null===(i=e.isCspNonceExperimentEnabled)||void 0===i||i}mapKeys(e){Object.keys(e).forEach(t=>{const i=`${o_}.${e[t]}`;this._translations[`${o_}.${t}`]=this._translations[i]})}getLocale(){return this._hasTranslations()?this._locale:r_}translate(e,t={}){var i;const n=`${o_}.${e}`;if("string"!=typeof this._translations[n])return this._logger.warn(`Translation key "${n}" is missing`),n;if(this._isCspNonceExperimentEnabled){this._formatters[n]||(this._formatters[n]=new je(this._escapeSpecialCharacters(this._translations[n]||""),this._locales[n],void 0,{ignoreTag:!0}));try{return this._formatters[n].format(this._transformData(t))}catch(e){if(this._isFormatError(e))return null!==(i=e.originalMessage)&&void 0!==i?i:"";throw e}}if(!this._formatters[n]){const e=new Ue(this._locales[n]);this._formatters[n]=e.compile(this._translations[n]||"")}return this._formatters[n](this._transformData(t))}_transformConfig(e={}){const t={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:e.locale||r_},i=e.locales||{},n=this._flattenObject(e.translations||{}),r=this._flattenObject(e.defaultTranslations||{}),o=this._flattenObject(e.fallbackTranslations||{});return ee(Object.keys(o),Object.keys(r),Object.keys(n)).forEach(a=>{var s,d;n&&n[a]?(t.translations[a]=n[a],t.locales[a]=i[a]||t.locale):r[a]?(t.translations[a]=r[a],t.locales[a]=null!==(s=e.defaultLocale)&&void 0!==s?s:r_):(t.translations[a]=o[a],t.locales[a]=null!==(d=e.fallbackLocale)&&void 0!==d?d:r_)}),t}_flattenObject(e,t={},i=""){try{Object.keys(e).forEach(n=>{const r=e[n],o=i?`${i}.${n}`:n;if(D(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,i)=>{const n=e[i];return t[i]=null==n?"":n,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''")}};a_=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],a_);const s_=a_;function d_(e={}){return new s_(e,gt())}let c_=class{constructor(e){this._storeConfig=e,this._customerFormatter=new No(this._storeConfig.shopperCurrency),this._storeFormatter=new No(this._storeConfig.currency)}toCustomerCurrency(e){const t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)}toStoreCurrency(e){return this._storeFormatter.format(e)}};c_=function(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}([xi],c_);const l_=c_;function u_(e){return new l_(e)}function h_(e){return e&&"ga"in e&&"function"==typeof e.ga}function p_(e,t){h_(window)&&window.ga("send",e,Object.assign(Object.assign({},t),{nonInteraction:!1}))}function m_(e){return y_(e).length>=8096}function y_(e){return Object.keys(e).reduce((t,i)=>{const n=typeof e[i];return"string"===n||"number"===n?[...t,`${i}=${e[i]}`]:"object"===n&&null!==e[i]?[...t,y_(e[i])]:t},[]).join("&")}var g_;!function(e){e[e.CUSTOMER=1]="CUSTOMER",e[e.SHIPPING=2]="SHIPPING",e[e.BILLING=3]="BILLING",e[e.PAYMENT=4]="PAYMENT"}(g_||(g_={}));const v_={customer:g_.CUSTOMER,shipping:g_.SHIPPING,billing:g_.BILLING,payment:g_.PAYMENT};class f_{constructor(e,t,i,{checkoutSteps:n}={}){if(this.checkoutService=e,this.analyticsExtraItemsManager=t,this.analytics=i,this._checkoutStarted=!1,this._completedSteps={},this._viewedSteps={},this._analyticStepOrder=["customer","shipping","billing","payment"],void 0!==n){if(n.some(e=>!(e in v_)))throw new Lt(`Invalid checkout steps provided. Valid values are: ${R(v_).join(", ")}.`);this._analyticStepOrder=n}}trackCheckoutStarted(){if(this._checkoutStarted)return;const e=this.getCheckout();if(!e)return;const{coupons:t,grandTotal:i,shippingCostTotal:n,taxTotal:r,cart:{lineItems:o,discountAmount:a,id:s}}=e,d=this.analyticsExtraItemsManager.saveExtraItemsData(s,o);this.analytics.track("Checkout Started",this.getTrackingPayload({revenue:i,shipping:n,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:i,orderId:n,orderAmount:r,shippingCostTotal:o,taxTotal:a,discountAmount:s,coupons:d,lineItems:c,cartId:l}=t;if(!i)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:n,revenue:r,shipping:o,tax:a,discount:s,coupons:d,extraItemsData:u,lineItems:c});if(h&&Kc(window)&&h_(window)&&m_(p))return p_("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=>{p_("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 i=this.getIdFromStep(t);if(!i)break;if(this.hasStepViewed(i)||this.trackViewed(i),i===e)break;this.hasStepCompleted(i)||this.trackCompleted(i)}}trackCompleted(e){const t=this.getSelectedShippingOption(),{code:i=""}=this.getShopperCurrency()||{},n=this.getPaymentMethodName(),r={step:e,currency:i};t&&(r.shipping_method=t.description),n&&(r.payment_method=n),r.shipping_method||r.payment_method||(r.shipping_method=" "),this.analytics.track("Checkout Step Completed",r);const o=t?t.id:"",a=e===g_.SHIPPING?`${e}-${o}`:e;this._completedSteps[a]=!0}getTrackingPayload({orderId:e,revenue:t,shipping:i,tax:n,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(i),tax:this.toShopperCurrency(n),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(),i=t?t.id:"";return Object.prototype.hasOwnProperty.call(this._completedSteps,e)||e===g_.SHIPPING&&Object.prototype.hasOwnProperty.call(this._completedSteps,`${e}-${i}`)}hasStepViewed(e){return!!this._viewedSteps[e]}getIdFromStep(e){const t=e.split(".");return v_[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 i=(t.customItems||[]).map(e=>({product_id:e.id,sku:e.sku,price:e.listPrice,quantity:e.quantity,name:e.name})),n=t.giftCertificates.map(e=>({product_id:e.id,price:this.toShopperCurrency(e.amount),name:e.name,quantity:1}));return[...i,...[...t.physicalItems,...t.digitalItems].map(t=>{let i;t.options&&t.options.length&&(i=t.options.map(e=>`${e.name}:${e.value}`),i.sort());const n=Array.isArray(i)&&i.length?i.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:n},r&&{brand:r})}),...n]}}class S_{trackCheckoutStarted(){}trackOrderComplete(){}trackStepViewed(){}trackStepCompleted(){}}function w_(e,t){const{data:i}=e.getState(),n=i.getConfig();if(!n)throw new Xe(We.MissingCheckoutConfig);const{isAnalyticsEnabled:r}=n.checkoutSettings;return r&&Kc(window)?new f_(e,new Yc(Te),window.analytics,t):new S_}function I_(e){return Boolean(e.hasOwnProperty("braintreeFastlane"))}class __{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"),i=null==t?void 0:t.initializationData.isBraintreeAnalyticsV2Enabled,n=I_(window)&&window.braintreeFastlane.events;return i&&n}_getBraintreeEventsOrThrow(){if(I_(window))return window.braintreeFastlane.events;throw new pn}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getBraintreeEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:i}=this._getBraintreeEventsOrThrow();i(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getBraintreeEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const i=this.checkoutService.getState(),n=i.data.getCart(),r=null===(e=i.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=i.data.getCustomer())||void 0===t?void 0:t.isGuest,a=i.data.getPaymentMethod("braintreeacceleratedcheckout"),s=[{treatment_group:!i.errors.getLoadPaymentMethodError("braintreeacceleratedcheckout")&&(null==a?void 0:a.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==n?void 0:n.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 i=(this.checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:i.length>1?"1":"0",apm_list:i.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 C_(e){return new __(e)}class b_{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,i=window,n=!!i.paypalFastlane&&!!i.paypalFastlane.events;return t&&n}_getPayPalEventsOrThrow(){const e=window;if(e.paypalFastlane&&e.paypalFastlane.events)return e.paypalFastlane.events;throw new pn}_trackEmailSubmitted(){const{emailSubmitted:e}=this._getPayPalEventsOrThrow();e(this._getEmailSubmittedEventOptions())}_trackApmSelected(e,t){const{apmSelected:i}=this._getPayPalEventsOrThrow();i(this._getApmSelectedEventOptions(e,t))}_trackOrderPlaced(e){const{orderPlaced:t}=this._getPayPalEventsOrThrow();t(this._getOrderPlacedEventOptions(e))}_getEventCommonOptions(){var e,t;const i=this._checkoutService.getState(),n=i.data.getCart(),r=null===(e=i.data.getConfig())||void 0===e?void 0:e.storeProfile,o=null===(t=i.data.getCustomer())||void 0===t?void 0:t.isGuest,a="paypalcommerceacceleratedcheckout",s=i.data.getPaymentMethod(a),d=[{treatment_group:!i.errors.getLoadPaymentMethodError(a)&&(null==s?void 0:s.initializationData.shouldRunAcceleratedCheckout)?"test":"control"}];return{context_type:"cs_id",context_id:(null==n?void 0:n.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 i=(this._checkoutService.getState().data.getPaymentMethods()||[]).map(({id:e})=>e);return Object.assign(Object.assign({},this._getEventCommonOptions()),{apm_shown:i.length>1?"1":"0",apm_list:i.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 P_(e){return new b_(e)}var O_;class E_{constructor(e,t){this._host=e,this._hostedFormFactory=t}submitStoredCard(e,t){return i=this,n=void 0,o=function*(){const i=this._hostedForm;if(!i)throw new pi(si.PaymentNotInitialized);yield i.validate().then(()=>i.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 i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(a,s)}d((o=o.apply(i,n||[])).next())});var i,n,r,o}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}function A_(e){const t=ZS();return new E_(e,new cy(t))}!function(e){e.CUSTOMER="customer",e.SHIPPING="shipping",e.BILLING="billing",e.PAYMENT="payment"}(O_||(O_={}));const T_=[O_.CUSTOMER,O_.SHIPPING,O_.BILLING,O_.PAYMENT];class k_{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 Xe(We.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:i,isComplete:n,orderId:r,orderAmount:o,shippingCostTotal:a,lineItems:s,cartId:d,coupons:c,channelId:l,taxTotal:u}=t;n&&this.bodlEvents.emitOrderPurchasedEvent({event_id:d,currency:i.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,i.code)})}stepCompleted(e){e&&T_.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={[O_.SHIPPING]:this._trackShippingStepCompleted.bind(this)}[e];t?t():this.bodlEvents.emit("bodl_checkout_step_completed",{step:e})}_trackShippingStepCompleted(){var e,t;const i=null===(t=null===(e=this.state)||void 0===e?void 0:e.getSelectedShippingOption())||void 0===t?void 0:t.description,n=this._getCommonCheckoutData();n&&i&&this.bodlEvents.emitShippingDetailsProvidedEvent(Object.assign(Object.assign({},n),{shipping_method:i}))}_getCommonCheckoutData(){var e;const t=null===(e=this.state)||void 0===e?void 0:e.getCheckout();if(!t)return null;const{cart:{cartAmount:i,currency:n,lineItems:r,id:o,coupons:a},channelId:s}=t;return{event_id:o,currency:n.code,cart_value:i,coupon_codes:a.map(e=>e.code.toUpperCase()),line_items:this._getProducts(r,n.code),channel_id:s}}_getProducts(e,t){const i=(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})),n=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[...i,...[...e.physicalItems,...e.digitalItems].map(e=>{let i;return e.options&&e.options.length&&(i=e.options.map(e=>`${e.name}:${e.value}`),i.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:(n=e,Array.isArray(n.categoryNames)?n.categoryNames:Array.isArray(n.categories)?_(n.categories).map(({name:e})=>e):[]),retail_price:e.retailPrice};var n}),...n].map(e=>Object.assign(Object.assign({},e),{product_id:String(e.product_id)}))}_hasStepCompleted(e){return this._completedSteps[e]}}class D_{checkoutBegin(){}orderPurchased(){}stepCompleted(){}customerEmailEntry(){}customerSuggestionInit(){}customerSuggestionExecute(){}customerPaymentMethodExecuted(){}showShippingMethods(){}selectedPaymentMethod(){}clickPayButton(){}paymentRejected(){}paymentComplete(){}exitCheckout(){}}function M_(e){return function(e){return"bodlEvents"in e}(window)?new k_(e,window.bodlEvents.checkout):new D_}export{Ri as ExtensionCommandType,Li as ExtensionQueryType,M_ as createBodlService,C_ as createBraintreeAnalyticTracker,qI as createCheckoutButtonInitializer,XS as createCheckoutService,u_ as createCurrencyService,n_ as createEmbeddedCheckoutMessenger,d_ as createLanguageService,P_ as createPayPalCommerceAnalyticTracker,w_ as createStepTracker,A_ as createStoredCardHostedFormService,n as createTimeout,JI as embedCheckout};
|
|
2
2
|
//# sourceMappingURL=checkout-sdk-essential.js.map
|